2015-04-23 37 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>