2011-09-03 95 views
1

我想知道,如何在jQuery加載後運行某些東西? jQuery是否得到了'我準備好'的事件?jQuery的加載速度比使用它的其他腳本慢

第一

在我getls.js

var script = document.createElement('script'); 
script.type = 'text/javascript'; 
script.src = 'http://example.com/setls.js'; 
document.getElementsByTagName('body')[0].appendChild(script); 

然後在setls.js

if (typeof jQuery == 'undefined') { 
    var script = document.createElement('script'); 
    script.type = 'text/javascript'; 
    script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js'; 
    document.getElementsByTagName('body')[0].appendChild(script); 
} 
var script = document.createElement('script'); 
script.type = 'text/javascript'; 
script.src = 'http://example.com/ls.js'; 
document.getElementsByTagName('body')[0].appendChild(script); 

ls.js

$("body").css("background-color", "green"); 

但ls.js加載速度比快的jQuery並告訴我Uncaught ReferenceError: $ is not defined。我該如何處理這個事件?謝謝您的幫助。

編輯:這是因爲這個腳本將類似谷歌分析,你知道。爲了讓用戶只使用一行腳本並在他的代碼中加載getls.js,將使他開心(哦,酷,它只有4行?需要)。但我也必須檢查jQuery,因爲我將在以後使用jQuery,如果已經得到它,我無法再加載它。在此之後,我想使用它。
所以它的不是約document.ready事件,該文件準備好之前,我開始加載jQuery。

+1

首先爲什麼的arent你加載的jQuery爲你的腳本聲明的一部分,sicne你正在使用jQuery爲什麼使用文檔對象和它的方法..:/ – Baz1nga

+0

他也想動態加載jQuery。 –

回答

2

您想要動態加載這兩個腳本。您有兩種選擇:

  1. 在您正在注入的腳本上使用onload。它在所有主流瀏覽器都支持,但在IE上測試它,因爲它幾年前在IE上不工作。這是一個乾淨的解決方案。
  2. 使用定時器輪詢jQuery變量的存在,使用typeof(window.jQuery)。當它被定義時,jQuery應該被加載。
+0

你的意思是'script.onreadystatechange'? –

+0

不,onload不僅適用於body,還適用於許多其他元素,其中包括img和腳本。一旦外部資源(img標籤的圖像,或腳本標籤的js文件)被加載,它就會啓動。 –

+0

英雄。 (typeof jQuery ==「undefined」){var script = document.createElement(「script」); script.type =「text/javascript」; script.setAttribute(「onLoad」,「lsinit( ) 「); script.src =」 https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js 「; document.getElementsByTagName(」 正文「)[0] .appendChild(腳本)}和ls.js中的lsinit函數(){$(「body」).css(「background-color」,「green」);}' –

2

,而不是一個競爭狀態,只是有JQuery的使用$.getScript()

$.getScript('http://example.com/ls.js', function(data, textStatus){ 
    console.log(data); //data returned 
    console.log(textStatus); //success 
    console.log('Load was performed.'); 
}); 

http://api.jquery.com/jQuery.getScript/

+0

neet,但我在那個時候沒有jquery。 :( –

+0

我知道:)相信我。 – AlienWebguy

0

包裝你的代碼到這個加載ls.js:

$(document).ready(function(){ 

//your code 

} 

這等待DOM以及所有要加載的腳本和css文件。並確保,jquery的 - 標記在之前添加您的javascript文件。

+1

'$(function(){'做同樣的事情,節省一些打字;) – AlienWebguy

+1

這是正確的,但爲了可讀性,我總是喜歡文檔的東西;) – GNi33

+0

-1這不是一個DOM就緒問題,這是一個推遲javascript loading race condition as @Alienwebguy says – Maverick

0

jQuery類型有一個「我準備好」事件。你想要做的是包裝你的代碼:

$(document).ready(function() { 
    // Your code here 
}); 

這將延緩準備文件中的代碼的執行,直到DOM和jQuery是滿載。另外,將所有腳本標籤放在頁面的底部是提高效率的好習慣。

+0

不行,它不是關於文檔準備好。 :P –

1

檢查在一個循環,直到jQuery將可用:

//Have to wait until jQuery will arrive 
function wait_for_jQuery(){ 
    if (typeof jQuery == 'undefined'){ 
     setTimeout(wait_for_jQuery, 50); 
    }else{ 
     $(document).ready(main()); 
    } 
} 
wait_for_jQuery(); 

function main(){ ... }; 
相關問題