![](/img/trans.png)
[英]Is placing script tag before </body> tag equivalent to jQuery's document.ready method
[英]document.ready when jQuery's before the body tag
<html>
<head>
<title>Hello</title>
</head>
<body>
<h1>Welcome</h1>
<script>
$(function() {
// $ is undefined
});
</script>
<script src="js/jquery.js"></script>
</body>
</html>
有沒有一種方法可以在執行功能之前等待文檔加載和加載jQuery?
您在引用$
之前就已經將其引用$
,但這根本行不通。
假設js/jquery.js
存在,這將起作用:
<script src="js/jquery.js"></script>
<script>
$(function() {
// your code goes here
});
</script>
由於第一個腳本標記將在第二個腳本標記引用之前定義$
。
@@ KevinB的Hattip指出了這一明顯的附加點。
如果腳本標簽位於頭部-加載腳本時該主體不存在。 因此,在運行javascript之前,通常使用准備就緒的文檔來確保html頁面存在。
如果腳本標簽位於頁面的底部,則在加載腳本時html已經存在,因此無需等待文檔就緒事件。 因此,js代碼變為:
<script src="js/jquery.js"></script>
<script>
// your code goes here
</script>
</body>
</html>
我覺得這不是一個好的解決方案,但是如果您確實需要,可以加載jQuery,類似於Google為其分析服務加載其JavaScript的方式。 之后,您可以編寫更多代碼來檢測加載完成的時間,並執行包含您要執行的操作的回調。
從本網站http://www.tlswebsolutions.com/how-to-include-jquery-dynamically-aka-check-to-see-if-it-exists/進行的粗略演示
if(!(window.jQuery)) {
var s = document.createElement('script');
s.setAttribute('src', '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js');
s.setAttribute('type', 'text/javascript');
document.getElementsByTagName('head')[0].appendChild(s);
}
為您簡化-
<html>
<head>
<title>Hello</title>
</head>
<body>
<h1>Welcome</h1>
<script src="js/jquery.js"></script>
<script>
$(function() {
// $ is undefined
});
</script>
</body>
從技術上講,您可以。
function main() {
if (! window.jQuery) {
setTimeout(main, 100);
return;
}
// Some code that uses jQuery
}
setTimeout(main, 100);
這似乎也有可能,但可能無法與舊版瀏覽器一起可靠地工作。
window.onload = function() {
// Some code that uses jQuery
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.