JavaScript:DOM 加载事件、执行顺序和 $(document).ready() [英] JavaScript: DOM load events, execution sequence, and $(document).ready()

查看:33
本文介绍了JavaScript:DOM 加载事件、执行顺序和 $(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>

以下是我的问题:

  1. 事情发生的顺序是什么?首先执行 DOM,然后执行 JS,是反之亦然,还是同时执行(或一旦 JS 文件下载完成,不考虑 DOM)?我知道脚本是按顺序加载的.

  1. 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 将按原样执行.通常,浏览器在看到

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆