Home >Web Front-end >JS Tutorial >How to dynamically load external Javascript files_javascript tips
I recently 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')[0].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-1.9.1.js",function(){ alert("动态加载的是jquery-1.9.1.js"); $(function(){ alert("jquery-1.9.1.js动态加载完成之后做的处理操作"); }); }); }else{ MiniSite.JsLoader.load("js/jquery-2.0.3.js",function(){ alert("动态加载的是jquery-2.0.3.js"); $(function(){ alert("jquery-2.0.3.js动态加载完成之后做的处理操作"); }); }); } </script> </head> <body> </body> </html>
The test results are as follows:
Test results under IE browser:
Test results under Google browser:
I will share with you how to use the js loader to dynamically load external Javascript files. I believe it will be of great help to everyone's learning.