如何在没有侦听器的情况下检查 DOM 是否已准备好?
如果我有一个动态加载的脚本,我希望它等到 DOM 准备好后再执行代码。但是,如果脚本加载太慢,则 DOM 已经准备好,因此 DOM-Ready 函数将不会运行。
请不要使用任何框架,我依赖于纯 JavaScript。
提前致谢!
If I have a script that is loaded dynamically, I want it to wait until the DOM is ready before executing code. However, if the script loads too slowly, the DOM will already be ready and therefore the DOM-Ready function will not run.
No frameworks, please, I'm relying on pure JavaScript.
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果没有监听器,就没有 100% 可靠的方法来确保加载整个 DOM。您可以执行以下操作:
这将等到您关心的某个目标元素存在。
Without a listener there's no 100% reliable way to ensure that the entire DOM is loaded. You can do something like this:
That'll wait until some target element you care about exists.
此页面的一部分: http://dean.edwards.name/weblog/2006 /06/again/ 你会发现这段代码,这就是我用来做你所问的事情的代码:
我用代码留下了评论,因为我没有写它:
Part way down on this page: http://dean.edwards.name/weblog/2006/06/again/ you will find this code, which is what I use to do what you are asking about:
I leave the comment with the code as I didn't write it:
非常简单 - 将脚本放在紧邻结束正文标记之前(如果有的话)。它不保证 DOM 已准备好,但它比 DOM 就绪侦听器更可靠,并且比加载侦听器更早运行。
Very simple - put your script immediately before the closing body tag (if you have one). It doesn't guarantee that the DOM is ready, but it's more reliable that DOM ready listeners and runs earlier than load listeners.
以下是几个纯 javascript domready 事件:
http://snipplr.com/view/6029/domreadyjs/
http://www.geekdaily.net/2007/07/27/javascript-windowonload-is-bad-mkay/
Here are a couple of pure javascript domready events:
http://snipplr.com/view/6029/domreadyjs/
http://www.geekdaily.net/2007/07/27/javascript-windowonload-is-bad-mkay/
检查 document.readyState
http://www.dustindiaz.com/smallest-domready-ever< 的 代码片段/a>
snippet that checks the document.readyState
http://www.dustindiaz.com/smallest-domready-ever