在另外一个问题,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,无论这些可能会失败。
脚本按照遇到的顺序加载,除非您设置了延迟或异步,所以这不是问题。 – adeneo
http://stackoverflow.com/questions/1828237/check-if-jquery-has-been-loaded-then-load-it-if-f-这个问题是非常类似于你的,并有非常好的答案 – JuniorDev
@ adeneo这显然是不正确的。请参阅“在Chrome浏览器中按顺序加载脚本”http://stackoverflow.com/questions/29785887/scripts-loading-out-of-order-in-chrome – Colin