2013-08-06 63 views
-1

我發現一個JavaScript加載功能是這樣的:負載在不同的JavaScript文件

function loadScript(srcs, f) { 

    var head = document.getElementsByTagName('head')[0]; 
    var script = document.createElement('script'); 
    script.src = src; 
    var done = false; 
    script.onload = script.onreadystatechange = function() { 
     // attach to both events for cross browser finish detection: 
     if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) { 
      done = true; 
      if (typeof f === 'function') 
       f(); 
      // cleans up a little memory: 
      script.onload = script.onreadystatechange = null; 
      head.removeChild(script); 
     } 
    }; 
    head.appendChild(script); 
}; 

它非常好加載一個文件,現在我想修改的功能,使得它可以在文件的陣列加載。我有這樣的代碼:

function loadScript(srcs, f) { 
    var head = document.getElementsByTagName('head')[0]; 

    for (var i = 0; i < srcs.length; i++) { 
     var script = document.createElement('script'); 
     script.src = srcs[i]; 
     var done = false; 
     script.onload = script.onreadystatechange = function() { 
      // attach to both events for cross browser finish detection: 
      if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) { 
       done = true; 
       if (typeof f === 'function') 
        f(); 
       // cleans up a little memory: 
       script.onload = script.onreadystatechange = null; 
       head.removeChild(script); 
      } 
     }; 
     head.appendChild(script); 
    } 
}; 

現在,如果我調用這個函數是這樣的:

loadScript(['testing_path1', 'testing_path2'], function() { 


}); 

即使testing_path2文件被加載,我不能叫內的職能。我想這是因爲JavaScript的異步功能。任何想法如何解決這個問題?

+0

的可能重複[如何包括另一個JavaScript JavaScript文件文件?(http://stackoverflow.com/questions/950087/how-to-include-a-javascript-file-in-another-javascript-文件) –

+0

你確定它仍然存在? (參考'head/removeChild(script)'位)。 – putvande

回答

0

你需要在你的代碼擺脫這一行:

head.removeChild(script); 

否則script標籤被立即再次刪除。