javascript $(document).ready() 什么时候触发?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17533150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When does $(document).ready() fire?
提问by Travesty3
The comments from this questiongot me thinking about something. When exactly does the $(document).ready()
function fire? The obvious answer would be "when the document is ready," but when exactly is that?
这个问题的评论让我想到了一些事情。$(document).ready()
函数什么时候触发?显而易见的答案是“文档准备好时”,但具体是什么时候?
For instance, if I turned output buffering on and flushed my output while PHP continued executing, wouldn't that send output to the browser? So is there any way the document could be ready before the PHP script has finished executing, or does the event wait until the request has finished?
例如,如果我打开输出缓冲并在 PHP 继续执行时刷新我的输出,那不会将输出发送到浏览器吗?那么有没有什么办法可以在 PHP 脚本完成执行之前准备好文档,或者事件是否等到请求完成?
EDIT:
编辑:
The responses seem to basically agree that the event fires when the client thinks it's ready.
响应似乎基本上同意,当客户端认为它已准备好时,事件就会触发。
To get a better understanding (which I should have probably done in the first place), I just set up a test:
为了更好地理解(我可能一开始就应该这样做),我只是设置了一个测试:
<?php ob_start(); ?>
<html>
<head>
<script type="text/javascript" src="lib/js/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
alert("READY");
});
</script>
</head>
<body>
<?php
ob_flush();
for ($i=0; $i<999999; $i++) {
echo "HELLO$i\n";
ob_flush();
}
?>
</body>
</html>
The result was that in this example, the contents began showing on the page right away, but the alert didn't happen until the loop was done, or the script timed out (30 seconds).
结果是,在本例中,内容立即开始显示在页面上,但直到循环完成或脚本超时(30 秒)才发生警报。
To the point of depending on which browser you use, I tried inserting this in my loop:
根据您使用的浏览器,我尝试将其插入到我的循环中:
if ($i == 99) {
echo "</body></html>";
}
And Chrome seemed to automatically correct it by putting those tags at the end of the page (as seen in the web dev inspector). Viewing the source of the page showed it in the middle, where I echo'ed it though.
Chrome 似乎通过将这些标签放在页面末尾来自动更正它(如 Web 开发检查器中所示)。查看页面的源代码将其显示在中间,但我在那里回应了它。
采纳答案by DaveRandom
jQuery's ready
event for the document fires as soon as jQuery determines that the DOM is accessible. The exact mechanism depends on the browser.
ready
一旦 jQuery 确定 DOM 可访问,就会触发文档的jQuery事件。确切的机制取决于浏览器。
Take a look at the relevant source code.
看看相关的源代码。
Firstly, there is a check to see if the DOM is already accessible at the point where an attempt was made to bind a listener to the event. If it is, the callbacks are scheduled to fire immediately - although they are not actually firedimmediately, to allow the code already occupying the current execution slot to cancel the handlers if required.
首先,检查在尝试将侦听器绑定到事件时是否已经可以访问 DOM。如果是,回调将被安排立即触发 - 尽管它们实际上不会立即触发,以允许已经占用当前执行槽的代码在需要时取消处理程序。
If the DOM is not yet accessible, an attempt is made to bind an event listener to the browser's native DOMContentLoaded
event - this is the "correct" native way to ask the browser to inform you when the DOM is available, but it's a relatively modern feature. If this is not possible (this almost certainly indicates you code is running in an older version of IE), the code falls back to a couple of mechanisms:
如果 DOM 尚不可访问,则会尝试将事件侦听器绑定到浏览器的本机DOMContentLoaded
事件 - 这是要求浏览器在 DOM 可用时通知您的“正确”本机方式,但它是一个相对现代的功能. 如果这是不可能的(这几乎可以肯定表明您的代码在旧版本的 IE 中运行),则代码将回退到以下几种机制:
- Try and attach to the
onreadystatechange
event of the document. This is not fool-proof and will be later thanDOMContentLoaded
would have been, but it's pretty good. - Fall back to the
load
event of thewindow
object. This will often be much later than the DOM is available, but it's a last-ditch failsafe to ensure the event will always fire eventually. - The worst case scenario: keep polling the DOM until it's accessible.
- 尝试附加到
onreadystatechange
文档的事件。这不是万无一失的,并且会比DOMContentLoaded
本来更晚,但它非常好。 - 回退到对象的
load
事件window
。这通常比 DOM 可用要晚得多,但这是确保事件最终总是会触发的最后一搏故障保护。 - 最坏的情况:继续轮询 DOM 直到它可以访问。
From a PHP perspective, it is possible(but unlikely) for this to occur before your PHP script has finished executing. There are situations (such as long-polling) where the event would fire before your script is finished, but this would only occur in older browsers. However, in these scenarios, you wouldn't (shouldn't) be using these events at all, you would simply place the appropriate <script>
elements in the body of the page to allow them to be executed as soon as they are loaded, without waiting for the rest of the DOM.
从 PHP 的角度来看,这可能(但不太可能)在 PHP 脚本执行完成之前发生。在某些情况下(例如长轮询),该事件会在您的脚本完成之前触发,但这只会发生在较旧的浏览器中。但是,在这些场景中,您根本不会(不应该)使用这些事件,您只需将适当的<script>
元素放置在页面正文中,以允许它们在加载后立即执行,而无需等待对于 DOM 的其余部分。
Personally, I never use any of these load-driven events, more or less for that reason. YMMV.
就我个人而言,我从不使用任何这些负载驱动的事件,或多或少出于这个原因。天啊。
回答by vol7ron
For instance, if I turned output buffering on and flushed my output while PHP continued executing, wouldn't that send output to the browser?
例如,如果我在 PHP 继续执行时打开输出缓冲并刷新我的输出,那不会将输出发送到浏览器吗?
Yes, it'd send output, but it doesn't mean the browser thinks the server has finished. I know it's not PHP, but I love the Perl article Suffering from Buffering. The document is ready when the UserAgent thinks it's ready. However, the browser will keep the socket open, while it still thinks it's receiving data and no END signal has been sent.
是的,它会发送输出,但这并不意味着浏览器认为服务器已经完成。我知道它不是 PHP,但我喜欢 Perl 文章Suffering from Buffering。当 UserAgent 认为文档准备就绪时,文档就准备好了。然而,浏览器将保持套接字打开,同时它仍然认为它正在接收数据并且没有发送 END 信号。
So is there any way the document could be ready before the PHP script has finished executing, or does the event wait until the request has finished?
那么有没有什么办法可以在 PHP 脚本完成执行之前准备好文档,或者事件是否等到请求完成?
Typically the browser will wait until the server finishes sending data. If you're flushing the output, it's possible the web server can timeout while the script is still running, for instance, I think Apache has a default of 2 minutes. If the server sends the end signal, your document has finished and your browser may prepare the DOM and fire the DOMReady event, even if your script is still running on the server.
通常浏览器会等到服务器完成发送数据。如果您正在刷新输出,则 Web 服务器可能会在脚本仍在运行时超时,例如,我认为 Apache 的默认值为 2 分钟。如果服务器发送结束信号,则您的文档已完成并且您的浏览器可能会准备 DOM 并触发 DOMReady 事件,即使您的脚本仍在服务器上运行。
Contrary to some other comments </body>
and </html>
are not good indicators of the DOM being ready, primarily because a page may be malformed (have misspellings or not include those end tags). In those cases, the browser will still render in Quirksmode and fire the DOMReady.
与其他一些评论相反</body>
,</html>
它们不是 DOM 准备好的良好指标,主要是因为页面可能格式错误(拼写错误或不包含这些结束标记)。在这些情况下,浏览器仍将在 Quirksmode 中呈现并触发 DOMReady。
回答by Dzulqarnain Nasir
According to the jQuery site, $( document ).ready()
will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
根据 jQuery 站点,$( document ).ready()
只有在页面文档对象模型 (DOM) 准备好执行 JavaScript 代码时才会运行。
Reference: http://learn.jquery.com/using-jquery-core/document-ready/
参考:http: //learn.jquery.com/using-jquery-core/document-ready/
回答by Dany Caissy
It fires after the the DOM hierarchy has been fully constructed and there is no more PHP code to execute (as PHP code is executed before the page is sent).
它在 DOM 层次结构完全构建并且没有更多的 PHP 代码要执行(因为 PHP 代码在发送页面之前执行)后触发。
This means that it is executed as soon as the page is received by the client. Other things may load afterwards, such as images, CSS and other Javascript.
这意味着它会在客户端收到页面后立即执行。之后可能会加载其他内容,例如图像、CSS 和其他 Javascript。
回答by Karl-André Gagnon
Document.ready()
is fired when the DOM is done loading. When all the HTML is present, DOM ready
event will fire.
Document.ready()
当 DOM 完成加载时触发。当所有 HTML 都存在时,DOMready
事件将触发。
PHP will not interferewith DOM ready
since PHP is a server-side coding language. It will be proccessed from the server, the server sends the requested page, then your broswer loads the page and the DOM ready
event fires.
PHP不会干扰DOM,ready
因为 PHP 是一种服务器端编码语言。它将从服务器处理,服务器发送请求的页面,然后您的浏览器加载页面并ready
触发DOM事件。
The difference between DOM ready
and window load
is that load will wait until everyimage/css is loaded. The tag is present in the HTML but the image isn't shown.
DOMready
和 window的区别在于load
load 会等到每个image/css 都加载完毕。该标记存在于 HTML 中,但未显示图像。
Basicly, we could say that DOM ready is fired when the browser reads the HTML closing tag (</html>
)
基本上,我们可以说当浏览器读取 HTML 结束标记 ( </html>
)