Home >Web Front-end >JS Tutorial >How does the JS loader dynamically load external js files
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(); } } } };
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>
The test results are as follows:
For more related articles on how the JS loader dynamically loads external js files, please pay attention to the PHP Chinese website!