es5中,一个在js中导入另一个js文件。

  这个函数很简单,唯一值得注意的一点是,需要在导入完成之后,执行里面的回调函数。

 1 // 导入js的函数
 2 function loadJS(url, callback) {
 3     var script = document.createElement('script'),
 4         fn = callback || function () { };
 5     script.type = 'text/javascript';
 6     script.defer = true;
 7     //IE
 8     if (script.readyState) {
 9         script.onreadystatechange = function () {
10             if (script.readyState == 'loaded' || script.readyState == 'complete') {
11                 script.onreadystatechange = null;
12                 fn();
13             }
14         };
15     } else {
16         //其他浏览器
17         script.onload = function () {
18             fn();
19         };
20     }
21     script.src = url;
22     document.getElementsByTagName('head')[0].appendChild(script);
23 }

猜你喜欢

转载自www.cnblogs.com/daniao11417/p/13389166.html