2012-02-09 42 views
1

我正在查找允許我使用JavaScript以非異步方式加載其他JavaScript文件的代碼。我試過這個:JavaScript - 如何以非異步方式加載外部腳本?

var script=document.createElement('script'); 
script.setAttribute("type","text/javascript"); 
script.setAttribute("src", "jquery.min.js"); 
document.getElementsByTagName("head")[0].appendChild(script); 

$("div.whatever").css("color","red"); 

但這並不奏效。它會插入腳本節點,但它會在jQuery加載之前繼續運行腳本的其餘部分。這最終失敗,因爲jQuery代碼嘗試運行時尚未由jQuery定義$

有沒有辦法來加載使用本地JS該腳本非異步?

+1

可能的重複:http://stackoverflow.com/questions/3248384/document-createelementscript-synchronously – 2012-02-09 16:41:56

+0

可能的重複[動態加載JavaScript同步](http://stackoverflow.com/questions/2879509/dynamically-loading- javascript-同步) – Bakudan 2012-02-09 16:42:49

+2

^- 可能重複的評論^^ – CompanyDroneFromSector7G 2012-02-09 16:44:08

回答

3

您可以使用<script>節點.onload事件處理程序,繼續/執行應腳本後執行任意代碼裝載,像

script.onload = function() { 
    // continune here 
}; 

,或者你可以嘗試將async標誌設置爲false

script.setAttribute("async", false); 

雖然前者的解決方案中可用的任何瀏覽器實際上的作品,後者可能會不old'ish瀏覽器支持。

0

而是裝載的同步,稍微好一點的想法可能是使用onload

script.onload = function() { 
    // $ is defined now 
}; 

// append it only now to make sure it does not load before setting onload 
document.getElementsByTagName("head")[0].appendChild(script); 
相關問題