如何在没有框架的情况下检查 DOM 是否准备就绪? [英] How to check if DOM is ready without a framework?
问题描述
这里和网络上的问题就像无数其他人一样 - 如何检查 DOM 是否已在 Javascript 中加载?但这里有一个问题:
The question is so like a zillion others here and on the web - How to check if DOM has loaded in Javascript? But here's the catch:
- 不使用jQuery等框架;
- 不知道您的脚本是通过静态放置的
<script>
标签加载的,还是在 DOM 加载后很久之后通过其他一些 Javascript 加载的.
- Without using a framework like jQuery etc;
- Without knowing if your script has been loaded via a statically placed
<script>
tag or via some other Javascript much later after the DOM has already loaded.
这是否可以或多或少地可靠地完成并具有跨浏览器兼容性?
Can this be done more or less reliably and with cross-browser compatibility?
添加: 让我澄清一下:我正在编写一个独立的 .JS 文件,它可以包含在任意网页中.我想在 DOM 加载之后执行代码.但我不知道如何将包含我的脚本.可以通过放置一个 标签(在这种情况下,传统的
onload
或 DOM-readiness 解决方案将起作用);或者它可以通过 AJAX 或其他方式加载,在 DOM 已经加载之后很久(所以前面提到的解决方案永远不会触发).
Added: Let me clarify: I'm writing a standalone .JS file which can be included in arbitrary webpages. I want to execute code AFTER the DOM has been loaded. But I don't know HOW my script will be included. It could be by placing a <script>
tag (in which case the traditional onload
or DOM-readiness solutions will work); or it could be loaded via AJAX or some other means, much later after the DOM is already loaded (so the previously mentioned solutions will never fire).
推荐答案
document.readyState
属性可用于检查文档是否准备就绪.来自 MDN:
The document.readyState
property can be used to check if the document is ready. From MDN:
文档的 readyState 可以是以下之一:
Values
The readyState of a document can be one of following:
- loading – 文档仍在加载.
- 交互式 – 文档已完成加载且文档已被解析,但图像、样式表和框架等子资源仍在加载.
- complete – 文档和所有子资源已完成加载.状态表明 load 事件即将触发.
- loading – The document is still loading.
- interactive – The document has finished loading and the document has been parsed but sub-resources such as images, stylesheets and frames are still loading.
- complete – The document and all sub-resources have finished loading. The state indicates that the load event is about to fire.
代码示例:
if(document.readyState === "complete") {
// Fully loaded!
}
else if(document.readyState === "interactive") {
// DOM ready! Images, frames, and other subresources are still downloading.
}
else {
// Loading still in progress.
// To wait for it to complete, add "DOMContentLoaded" or "load" listeners.
window.addEventListener("DOMContentLoaded", () => {
// DOM ready! Images, frames, and other subresources are still downloading.
});
window.addEventListener("load", () => {
// Fully loaded!
});
}
这篇关于如何在没有框架的情况下检查 DOM 是否准备就绪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!