javascript 动态加载javascript文件

 1     /*
 2         loadFile(data, callback): 动态加载js文件
 3         data: 存放需要加载的js文件的url("url" || ["url", "url"])
 4         callback: 加载完成回调函数
 5     */
 6     function loadFile(data, callback){
 7         if(!data){return;}
 8         let k, arr = [], el = document.body;
 9         if(typeof(data) === 'string'){arr.push(data);}
10         else if(Array.isArray(data) === true){for(k in data){arr.push(data[k]);}}
11         else{return;}
12         
13         let load = (url, suc, err)=>{
14             let script = document.createElement('script');
15             script.type = "text/javascript";//type = 'module';
16             script.src = url;
17             el.appendChild(script);
18             script.onload = function (e){if(typeof(suc) === "function"){suc(e);}}
19             script.onerror = function (e){if(typeof(err) === "function"){err(e);}}
20         }
21         
22         let timeout = ()=>{
23             if(t === len){if(typeof(callback) === "function"){callback(t, len, arr);} return;}
24             setTimeout(timeout, 1000);
25         }
26         
27         let len = arr.length, t = 0;
28         for(k in arr){load(arr[k], (e)=>{t++;});}
29         timeout();
30     }
31     //调用
32     loadFile("./main.js", (t, len, arr)=>{document.write(t+" "+len+" "+arr)});
33     loadFile(["./main.js", "./init.js"], (t, len, arr)=>{document.write(t+" "+len+" "+arr)});

 

posted @ 2020-02-16 14:46  鸡儿er  阅读(317)  评论(0编辑  收藏  举报