<分区>
我们经常在这里和那里读到,我们必须将我们的 js 代码放在页面头部或之前(抱歉)结束主体标记。关于这个的讨论放在一边,我只是想知道浏览器对这些东西的阅读顺序是什么(假设他们在这里表现得是平等的):
我们可以放置:
$(document).ready(function(){
无论在页面结构的哪个位置,因为我们正在使用 $(document).ready
还是应该将它放在 head 部分?
谁能澄清一下。
如果我的问题不清楚,我可以重新措辞。
<分区>
我们经常在这里和那里读到,我们必须将我们的 js 代码放在页面头部或之前(抱歉)结束主体标记。关于这个的讨论放在一边,我只是想知道浏览器对这些东西的阅读顺序是什么(假设他们在这里表现得是平等的):
我们可以放置:
$(document).ready(function(){
无论在页面结构的哪个位置,因为我们正在使用 $(document).ready
还是应该将它放在 head 部分?
谁能澄清一下。
如果我的问题不清楚,我可以重新措辞。
最佳答案
您可以将 脚本放在文档中的任何位置。最佳实践通常建议将脚本放在页脚中以解决页面加载性能问题。此外,最佳实践通常建议将脚本放在一起以便于维护。
但是,根据规范,对于在文档中放置 script
标记的位置没有限制。您可以将它们一起放在标题中、正文底部、散布在整个文档中,或者它们的任意组合。
使用 jQuery 构造 $(document).ready
具有相同的结果,无论它被放置在文档中的什么位置。关键是理解这个结构背后的功能:
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received.
所以,ready
与document.onload
类似,但又不相同。代码在哪里并不重要,如果您在 document.onload
被触发时或 jQuery 触发 ready
时执行它。代码在文档中的位置只有在未被某些事件处理程序/监听器包装时才有意义。
$(document).ready
位置的唯一限制是它不能在包含 jQuery 库之前发生。 $(document).ready
使用的是 jQuery,所以如果 jQuery 不存在....你不能使用它。
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
alert('executed as soon as it is reached (as the document is downloaded)');
$(document).ready(function () { alert('on jQuery ready'); });
</script>
</head>
<body onload="alert('executed on document.onload event');">
<script>
alert('executed as soon as it is reached (as the document is downloaded)');
$(document).ready(function () { alert('on jQuery ready'); });
</script>
</body>
</html>
文档
就绪
- http://api.jquery.com/ready/ 关于javascript - $(document).ready(function()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17659121/