文档:readyState 属性
Document.readyState 属性描述了 document 的加载状态。当此属性的值发生变化时,会在 document 对象上触发一个 readystatechange 事件。
值
文档的 readyState 可以是以下之一
loading-
document仍在加载中(即,HTML 解析器仍在工作)。 interactive-
文档已解析,但子资源(如延迟脚本和模块脚本、图像、样式表和框架)仍在加载。一旦进入此状态,并且延迟脚本和模块脚本已执行,就会触发
DOMContentLoaded事件。 完成-
文档和所有子资源已完成加载。该状态表示
load事件即将触发。
示例
不同的就绪状态
js
switch (document.readyState) {
case "loading":
// The document is loading.
break;
case "interactive": {
// The document has finished loading and we can access DOM elements.
// Sub-resources such as scripts, images, stylesheets and frames are still loading.
const span = document.createElement("span");
span.textContent = "A <span> element.";
document.body.appendChild(span);
break;
}
case "complete":
// The page is fully loaded.
console.log(
`The first CSS rule is: ${document.styleSheets[0].cssRules[0].cssText}`,
);
break;
}
readystatechange 作为 DOMContentLoaded 事件的替代方案
js
// Alternative to DOMContentLoaded event
document.onreadystatechange = () => {
if (document.readyState === "interactive") {
initApplication();
}
};
readystatechange 作为 load 事件的替代方案
js
// Alternative to load event
document.onreadystatechange = () => {
if (document.readyState === "complete") {
initApplication();
}
};
readystatechange 作为事件监听器,在 DOMContentLoaded 之前插入或修改 DOM
js
document.addEventListener("readystatechange", (event) => {
if (event.target.readyState === "interactive") {
initLoader();
} else if (event.target.readyState === "complete") {
initApp();
}
});
规范
| 规范 |
|---|
| HTML # current-document-readiness |
浏览器兼容性
加载中…