document.readyState

Document.readyState 属性描述了document 的加载状态。

当该属性值发生变化时,会在 document 对象上触发 readystatechange 事件。

语法

var string = document.readyState;

一个文档的 readyState 可以是以下之一:

loading(正在加载)
document 仍在加载。
interactive(可交互)
文档已被解析,"正在加载"状态结束,但是诸如图像,样式表和框架之类的子资源仍在加载。
complete(完成)
文档和所有子资源已完成加载。表示 load 状态的事件即将被触发。

示例

不同的准备状态

switch (document.readyState) {
  case "loading":
    // 表示文档还在加载中,即处于“正在加载”状态。
    break;
  case "interactive":
    // 文档已经结束了“正在加载”状态,DOM元素可以被访问。
    // 但是像图像,样式表和框架等资源依然还在加载。
    var span = document.createElement("span");
    span.textContent = "A <span> element.";
    document.body.appendChild(span);
    break;
  case "complete":
    // 页面所有内容都已被完全加载.
    let CSS_rule = document.styleSheets[0].cssRules[0].cssText;
    console.log(`The first CSS rule is: ${CSS_rule }`);
    break;
}

模拟 DOMContentLoaded 事件的 readystatechange

// 模拟 DOMContentLoaded/ jquery ready
document.onreadystatechange = function () {
  if (document.readyState === "interactive") {
    initApplication();
  }
}

模拟 load 事件的 readystatechange

// 模拟 load 事件
document.onreadystatechange = function () {
  if (document.readyState === "complete") {
    initApplication();
  }
}

在 DOMContentLoaded 之前使用 readystatechange 作为事件处理程序以插入或修改DOM

document.addEventListener('readystatechange', event => {
  if (event.target.readyState === 'interactive') {
    initLoader();
  }
  else if (event.target.readyState === 'complete') {
    initApp();
  }
});

规范

规范 状态 注释
HTML Living Standard
Document readiness
Living Standard
HTML 5.1
Document readiness
Recommendation
HTML5
Document readiness
Recommendation Initial specification.

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
readyStateChrome Full support 1Edge Full support 12Firefox Full support 4IE Full support 11
Full support 11
No support 9 — 11
Notes
Notes Internet Explorer 9 and 10 have bugs where the 'interactive' state can be fired too early before the document has finished parsing.
No support 8 — 9
Notes
Notes Only supports 'complete'.
Opera Full support 11
Notes
Full support 11
Notes
Notes Opera Presto fires 'complete' late after the 'load' event (in an incorrect order as per HTML5 standard specification).
Safari Full support 1WebView Android Full support 1Chrome Android Full support 18Firefox Android Full support 4Opera Android Full support 11
Notes
Full support 11
Notes
Notes Opera Presto fires 'complete' late after the 'load' event (in an incorrect order as per HTML5 standard specification).
Safari iOS Full support 1Samsung Internet Android Full support 1.0

Legend

Full support  
Full support
See implementation notes.
See implementation notes.

参见