2011-04-07 46 views
10

我想在myjs.js文件中包含jquery.js。我爲此寫了下面的代碼。如何將jquery.js包含在另一個js文件中?

var theNewScript=document.createElement("script"); 
    theNewScript.type="text/javascript"; 
    theNewScript.src="http://example.com/jquery.js"; 
    document.getElementsByTagName("head")[0].appendChild(theNewScript); 
    $.get(myfile.php); 

第5行顯示錯誤'$ not defined'。我想包含jquery.js,然後在myjs.js文件中調用$ .get()函數。我怎樣才能做到這一點? 請幫我

+0

爲什麼你想要在頁面之外使用$ .get()? – Calum 2011-04-07 08:05:50

+0

我假設你打算說'$ .get(「myfile.php」);'而不是'$ .get(myfile.php);'。 – 2011-04-07 08:22:43

+0

[檢查jquery是否已被加載,然後加載它如果爲false]可能的重複(http://stackoverflow.com/questions/1828237/check-if-jquery-has-been-loaded-then-load-it-if - 假) – 2014-06-01 08:25:33

回答

10

追加的文件頭中的腳本標籤編程並不一定意味着該腳本將可用立即。您應該等待瀏覽器下載該文件,解析並執行它。某些瀏覽器會觸發onload事件,以查看可以將邏輯連接起來的腳本。但這不是一個跨瀏覽器的解決方案。我寧願「輪詢」一個特定的符號變得可用,像這樣:

var theNewScript = document.createElement("script"); 
theNewScript.type = "text/javascript"; 
theNewScript.src = "http://example.com/jquery.js"; 
document.getElementsByTagName("head")[0].appendChild(theNewScript); 
// jQuery MAY OR MAY NOT be loaded at this stage 
var waitForLoad = function() { 
    if (typeof jQuery != "undefined") { 
     $.get("myfile.php"); 
    } else { 
     window.setTimeout(waitForLoad, 1000); 
    } 
}; 
window.setTimeout(waitForLoad, 1000); 
+0

哪些瀏覽器不支持onload事件?即使在IE 7之類的舊版瀏覽器中,它也能正常工作。 – Christophe 2013-03-05 17:56:29

+1

我已閱讀(但未親自確認)腳本標記的'onload'事件適用於壁虎,歌劇等,而對於IE,您需要掛鉤'onreadystatechange'。請參閱http://unixpapa.com/js/dyna.html和http://blog.lexspoon.org/2009/12/detecting-download-failures-with-script.html – 2013-03-05 18:11:06

+0

確實,您稱之爲事件的方式處理程序取決於瀏覽器。我使用現代瀏覽器的addEventListener和舊IE的attachEvent,工作得很好。 – Christophe 2013-03-05 18:15:53

4

問題是腳本不能立即加載,需要一段時間才能將腳本文件下載到您的頁面並執行(如果是jQuery來定義$)。我想推薦你使用HeadJS。那麼你可以這樣做:

head.js("/path/to/jQuery.js", function() { 
    $.get('myfile.php'); 
}); 
+1

這個。解決了。所有。我的。問題。謝謝。 – andufo 2011-12-12 06:40:42

0

答案很簡單,不要。 jQuery文件 對入侵者非常敏感,所以不要嘗試 。加入其他文件到jQuery 文件中經常會導致JS 控制檯出錯,PLUS jQuery未初始化爲 ,直到文件加載到主文件 中。

對不起,劃傷了。不知道你在做什麼。

試試這個:

var s = document.createElement('script'); 
s.type = 'text/javascript'; 
s.async = true; 
s.src = 'http://domain.com/jquery.js'; 
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(s); 
0

我之前用這個代碼,它的工作:

var t=document; 
var o=t.createElement('script'); 
o=t.standardCreateElement('script'); 
o.setAttribute('type','text/javascript'); 
o.setAttribute('src','http://www.example.com/js/jquery-1.3.2.js'); 
t.lastChild.firstChild.appendChild(o); 
相關問題