Home > Web Front-end > JS Tutorial > How does the JS loader dynamically load external js files

How does the JS loader dynamically load external js files

高洛峰
Release: 2016-12-28 13:43:24
Original
1344 people have browsed it

Today I found a js loader on the Internet that can dynamically load js files. The specific code is as follows:

JsLoader.js

var MiniSite=new Object();
/**
* 判断浏览器
*/
MiniSite.Browser={ 
ie:/msie/.test(window.navigator.userAgent.toLowerCase()), 
moz:/gecko/.test(window.navigator.userAgent.toLowerCase()), 
opera:/opera/.test(window.navigator.userAgent.toLowerCase()), 
safari:/safari/.test(window.navigator.userAgent.toLowerCase()) 
};
/**
* JsLoader对象用来加载外部的js文件
*/
MiniSite.JsLoader={
/**
* 加载外部的js文件
* @param sUrl 要加载的js的url地址
* @fCallback js加载完成之后的处理函数
*/
load:function(sUrl,fCallback){ 
var _script=document.createElement('script'); 
_script.setAttribute('charset','gbk'); 
_script.setAttribute('type','text/javascript'); 
_script.setAttribute('src',sUrl); 
document.getElementsByTagName('head')[].appendChild(_script); 
if(MiniSite.Browser.ie){ 
_script.onreadystatechange=function(){ 
if(this.readyState=='loaded'||this.readyStaate=='complete'){ 
//fCallback();
if(fCallback!=undefined){
fCallback(); 
}
} 
}; 
}else if(MiniSite.Browser.moz){ 
_script.onload=function(){ 
//fCallback(); 
if(fCallback!=undefined){
fCallback(); 
}
}; 
}else{ 
//fCallback();
if(fCallback!=undefined){
fCallback(); 
}
} 
} 
};
Copy after login

JsLoader.js test

<!DOCTYPE HTML>
<html>
<head>
<!--引入js加载器 -->
<script type="text/javascript" src="js/JsLoader.js"></script>
<title>JsLoaderTest.html</title>
<script type="text/javascript">
if(MiniSite.Browser.ie){
//动态加载Js
MiniSite.JsLoader.load("js/jquery-...js",function(){
alert("动态加载的是jquery-...js");
$(function(){
alert("jquery-...js动态加载完成之后做的处理操作");
});
}); 
}else{
MiniSite.JsLoader.load("js/jquery-...js",function(){
alert("动态加载的是jquery-...js");
$(function(){
alert("jquery-...js动态加载完成之后做的处理操作");
});
});
}
</script>
</head>
<body>
</body>
</html>
Copy after login

The test results are as follows:

How does the JS loader dynamically load external js files

For more related articles on how the JS loader dynamically loads external js files, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template