2011-01-24 74 views
2

由於我無法控制的原因,我必須通過動態附加的<script>標籤加載jQuery,並且僅在某些任意事件時執行此操作,而不是在做任何事件時執行此操作,在頁面加載時爲

我的問題是在檢測的時刻jQuery是準備好了,下面的代碼無法正常工作:

(function(){ 
    var s=document.createElement('script'); 
    s.setAttribute('type','text/javascript'); 
    s.setAttribute('src','http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js'); 
    document.getElementsByTagName('head')[0].appendChild(s); 
})() 

$(document).ready(function() { 
    // something that uses jquery and currently doesn't work 
}); 

如何檢測的時刻jQuery是準備在這個特定的配置中使用?

在此先感謝

+0

是JS的FILA總是動態加載? – 2011-01-24 14:21:07

+0

動態加載的javascript文件是如何做的? – 2011-01-24 14:23:21

+0

可能重複。去檢查這些問題: - http://stackoverflow.com/questions/3032721/async-load-javascript-files-with-callback - http://stackoverflow.com/questions/4249030/load-javascript-async-then- check-dom-loaded-before-execution-callback – 2011-01-24 14:23:06

回答

2

使用onloadonreadystatechange事件處理程序:

var scr = document.createElement('script'), 
    head  = document.getElementsByTagName('head')[0]; 

scr.onload = scr.onreadystatechange = function(){ 
     if(scr.readyState){ 
      if(scr.readyState === 'complete' || scr.readyState === 'loaded'){ 
       scr.onreadystatechange = null;             
       myReadyFunc(); 
      } 
     } 
     else{        
       myReadyFunc();   
     } 
}; 

head.insertBefore(scr, head.firstChild); 

function myReadyFunc() { 
    $(document).ready(function() { 
     // something that uses jquery and currently doesn't work 
    }); 
} 
1

您可以處理<script>元素的onreadystatechange事件,並且,如果this.readyStatecompleteloaded,運行功能。
對於Firefox,請處理onload事件。

你可以在一個包裝函數中公開這個函數,該函數接受一個函數作爲參數,並且如果jQuery已經被加載,或者如果它沒有被加載,則將其放入數組中(以在調用裝入處理程序中)調用它。

+0

只適用於Internet Explorers。 – jAndy 2011-01-24 14:24:40

1

一個老派的答案:) 您可以創建一個檢查,看看是否$對象存在如遞歸查詢功能:

function poller(){ 
    if($.length != 0){ 
     //do what you want 

    }else{ 
     setTimeout(poller, 100); 
    }  
} 

而加載運行輪詢功能的jQuery腳本之後。

相關問題