JavaScript:DOM 加载事件、执行顺序和 $(document).ready() [英] JavaScript: DOM load events, execution sequence, and $(document).ready()
问题描述
我刚刚意识到我缺乏对页面加载到浏览器时到底发生了什么的基本知识.
I just realized that I lack the fundamental knowledge of what exactly happens as a page is being loaded into a browser.
假设我有这样的结构:
<head>
<script src="jquery.js" type="text/javascript"></script>
<script src="first.js" type="text/javascript"></script>
</head>
<body>
...
<script type="text/javascript" id="middle">
// some more JS here...
</script>
...
<script src="last.js" type="text/javascript"></script>
</body>
以下是我的问题:
事情发生的顺序是什么?首先执行 DOM,然后执行 JS,是反之亦然,还是同时执行(或一旦 JS 文件下载完成,不考虑 DOM)?我知道脚本是按顺序加载的.
What sequence are things happening in? First the DOM then the JS is executed, is it vice-versa, or is it simultaneous (or as soon as the JS files finish downloading, without any regard to the DOM)? I know that scripts are loaded in order.
$(document).ready()
适合哪里? 在 Firebug 的 Net 选项卡中,我看到 DOMContentLoaded
事件和load
事件.$(document).ready()
是否在 DOMContentLoaded
事件触发时触发?找不到任何具体信息(每个人都只提到加载 DOM 时").
Where does $(document).ready()
fit in? In Firebug's Net tab I see DOMContentLoaded
event and the load
event. Is $(document).ready()
triggered when the DOMContentLoaded
event fires? Couldn't find any concrete info on this (everyone merely mentions "when the DOM is loaded").
加载 DOM 时"究竟是什么意思?所有的 HTML/JS 都已经被浏览器下载并解析了吗?还是只是 HTML?
What exactly does "when the DOM is loaded" mean? That all HTML/JS has been downloaded and parsed by the browser? Or just the HTML?
是否可能出现以下情况:有一个 $(document).ready()
调用 last.js
中的代码,但在最后一个之前运行.js加载了吗?它最有可能在哪里(在 first.js
或内联代码块中)?我该如何防止这种情况发生?
Is the following scenario possible: there is a $(document).ready()
which calls code in last.js
, but runs before last.js has loaded? Where would it most likely be (in first.js
or the inline code block)? How can I prevent this scenario?
我想了解什么时候发生什么以及什么取决于什么(如果有的话)的大局.
I want to undestand the big picture of what happens when and what depends on what (if at all).
推荐答案
Javascript 将按原样执行.通常,浏览器在看到 标签后立即停止解析页面,下载并运行脚本,然后继续运行.这就是为什么通常建议将
<script>
标签放在底部的原因:这样在浏览器等待脚本下载时用户不会有空白页面.
Javascript is executed as it is seen. Usually, the browser stops parsing the page as soon as it sees a <script>
tag, downloads and runs the script, and then keeps going. This is why it's commonly advised to put <script>
tags at the bottom: so the user doesn't have a blank page while the browser waits for the scripts to download.
但是,从 Firefox 3.5 开始,脚本会在后台下载,而页面的其余部分会呈现.在脚本使用 document.write
或类似的现在不寻常的事件中,Firefox 将根据需要进行备份和重绘.我认为目前其他浏览器不会这样做,但如果它即将到来我不会感到惊讶,并且 IE 至少支持