Document:readyState 属性
**Document.readyState
** 属性描述了document
的加载状态。当此属性的值发生变化时,readystatechange
事件将在 document
对象上触发。
值
示例
不同的就绪状态
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 标准 # 当前文档就绪状态 |
浏览器兼容性
BCD 表格仅在浏览器中加载
另请参阅
- 相关事件