2015-04-23 61 views
2

在另外一個問題,StackOverflow的建議,這是不可能保證在哪一個瀏覽器將處理<script>標籤的順序,無論其位置在<head><body>(見註釋):

Scripts loading out of order in Chrome

頂端回答建議使用pure-javascript「DOM-loaded」來保證所有依賴項都被加載,然後運行特定於頁面的代碼。

這使我懷疑是否是安全的使用jQuery的建議$函數作爲純JS DOM加載的替代品:

// Shorthand for $(document).ready() 
$(function() { 
    console.log("ready!"); 
}); 

源:http://learn.jquery.com/using-jquery-core/document-ready/

我怎麼能保證jQuery的$意志被定義?

編輯:請求假設失敗的例子。這裏有一個與<body>外部<script>

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
    <meta charset="utf-8"> 
    <title>Example 1</title> 
    </head> 
    <body> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
    <script> 
    $(function(){ 
     alert("Loaded."); 
    }); 
    </script> 
    </body> 
</html> 

而且一個與<head>外部<script> ...

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
    <meta charset="utf-8"> 
    <title>Example 1</title> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
    </head> 
    <body> 
    <script> 
    $(function(){ 
     alert("Loaded."); 
    }); 
    </script> 
    </body> 
</html> 

基於Scripts loading out of order in Chrome,無論這些可能會失敗。

+8

腳本按照遇到的順序加載,除非您設置了延遲或異步,所以這不是問題。 – adeneo

+0

http://stackoverflow.com/questions/1828237/check-if-jquery-has-been-loaded-then-load-it-if-f-這個問題是非常類似於你的,並有非常好的答案 – JuniorDev

+1

@ adeneo這顯然是不正確的。請參閱「在Chrome瀏覽器中按順序加載腳本」http://stackoverflow.com/questions/29785887/scripts-loading-out-of-order-in-chrome – Colin

回答

1

這個問題是基於一個錯誤的前提。引用的問題Scripts loading out of order in Chrome適用於使用TurboLink的應用程序,該應用程序可將靜態網站有效地轉換爲單頁應用程序。結果,我的<script>標籤被動態地插入,並且不能保證它們按順序運行。

0

你可以重複檢查jQuery是否加載,直到它,在這一點上你運行一些代碼。

<script> 
function doStuff() { 
    //do jQuery stuff 
} 

function checkLoaded() { 
    if(typeof jQuery == 'undefined') { 
     setTimeout(function() { 
     checkLoaded(); 
     }, 50); 
    } else { 
     doStuff(); 
    } 
} 

checkLoaded(); 
</script>