10.添加script标签,判断onload是否完成

  1. class Tools  
  2. {  
  3.     static loadScript(url, callback)  
  4.     {  
  5.         let old_script = document.getElementById(url);  
  6.         if (old_script)  
  7.         {  
  8.             if (old_script.ready == true)  
  9.             {  
  10.                 // console.log("INFO:already load:" + url);  
  11.                 callback();  
  12.                 return;  
  13.             }  
  14.             else  
  15.             {  
  16.                 document.body.removeChild(old_script);  
  17.                 // console.log("INFO:remove an old script that not ready:" + url);  
  18.             }  
  19.         }  
  20.         let script = document.createElement('script');  
  21.         script.id = url;  
  22.         script.src = url;  
  23.         script.onload = script.onreadystatechange = function() {  
  24.             if (script.ready) {  
  25.                 return false;  
  26.             }  
  27.             if (!script.readyState //这是FF的判断语句,因为ff下没有readyState这个值,IE的readyState肯定有值  
  28.                 || script.readyState == "loaded" || script.readyState == 'complete' // 这是IE的判断语句  
  29.             ) {  
  30.                 // console.log("INFO:load:" + url);  
  31.                 script.ready = true;  
  32.                 callback();  
  33.             }  
  34.         };  
  35.         document.body.appendChild(script);  
  36.     }  
  37.   
  38.     //synchronization  
  39.     //同步加载多个脚本  
  40.     static syncLoadScripts(scripts, callback)  
  41.     {  
  42.         var ok = 0;  
  43.         var loadScript = function(url) {  
  44.             Tools.loadScript(url, function(){  
  45.                 ok++;  
  46.                 // console.log("init:" + url)  
  47.                 if (ok == scripts.length) {  
  48.                     callback();  
  49.                 }  
  50.                 else {  
  51.                     loadScript(scripts[ok])  
  52.                 }  
  53.             })  
  54.         }  
  55.         loadScript(scripts[0]);  
  56.     }  
  57.   
  58.     //asynchronization  
  59.     //异步加载多个脚本  
  60.     static asyncLoadScripts(scripts, callback)  
  61.     {  
  62.         var ok = 0;  
  63.         for (var i=0; i < scripts.length; i++) {  
  64.             Tools.loadScript(scripts[i], function() {  
  65.                 console.log(scripts[ok])  
  66.                 ok++;  
  67.                 if (ok==scripts.length)  
  68.                 {  
  69.                     callback();  
  70.                 }  
  71.             })  
  72.         }  
  73.     }  
  74. }  
  75.   
  76. export default Tools;  
posted @ 2018-06-14 09:54  大耳朵小虎  阅读(385)  评论(0编辑  收藏  举报