Javascript 在 JQuery 中,如何检查 DOM 是否准备就绪?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8373910/
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
In JQuery, how do I check if the DOM is ready?
提问by TIMEX
Possible Duplicate:
javascript domready?
可能重复:
javascript domready?
I want to check whether $(function(){ });is "ready".
我想检查是否$(function(){ });“准备好”。
Return true if DOM is ready, false otherwise
如果 DOM 准备好返回真,否则返回假
回答by Sudhir Bastakoti
From jQuery code
来自 jQuery 代码
if ( jQuery.isReady ) {
fn.call( document, jQuery );
}
回答by ma?ek
You can use the explicit call
您可以使用显式调用
$(document).ready(function(){
// do this after dom is ready
});
Or use the shortcut
或者使用快捷方式
$(function(){
// do this after dom is ready
});
It's also useful to wrap your jQuery in an anonymous function when you're using other libraries; Also very common to use this when writing jQuery plugins.
当您使用其他库时,将 jQuery 包装在匿名函数中也很有用;在编写 jQuery 插件时使用它也很常见。
(function($, window){
// use $ here freely if you think any other library might have overridden it outside.
$(function(){
// do this after dom is ready
});
})(jQuery, window);
Lastly, you can use jQuery.isReady(bool)
最后,您可以使用jQuery.isReady(bool)
if (jQuery.isReady) {
// do something
}
回答by landons
That function will only execute when the dom is ready. That's the point of wrapping your code in that function ;). Having said that, some things (like images, deferred scripts, etc.) might not be fully loaded or rendered yet, so be aware.
该函数只会在 dom 准备好时执行。这就是将代码包装在该函数中的重点;)。话虽如此,有些东西(如图像、延迟脚本等)可能尚未完全加载或呈现,因此请注意。
回答by Sophie Alpert
You can use jQuery.isReady, but it's undocumented and should be avoided.
您可以使用jQuery.isReady,但它没有记录,应该避免使用。
If you just need to run something after the DOM is ready, you can just call
如果你只需要在 DOM 准备好后运行一些东西,你可以调用
$(document).ready(function() {
...
});
as normal – that will run the code immediately if the DOM is ready and wait until it is if not.
像往常一样 - 如果 DOM 准备好,它将立即运行代码,如果没有,则等待它。

