Document.readyState - Web APIs 编辑

The Document.readyState property describes the loading state of the document.

When the value of this property changes, a readystatechange event fires on the document object.

Syntax

var string = document.readyState;

Values

The readyState of a document can be one of following:

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.

Examples

Different states of readiness

switch (document.readyState) {
  case "loading":
    // The document is still loading.
    break;
  case "interactive":
    // The document has finished loading. We can now access the DOM elements.
    // But sub-resources such as images, stylesheets and frames are still loading.
    var 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 as an alternative to DOMContentLoaded event

// Alternative to DOMContentLoaded event
document.onreadystatechange = function () {
  if (document.readyState === 'interactive') {
    initApplication();
  }
}

readystatechange as an alternative to load event

// Alternative to load event
document.onreadystatechange = function () {
  if (document.readyState === 'complete') {
    initApplication();
  }
}

readystatechange as event listener to insert or modify the DOM before DOMContentLoaded

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

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'Document readiness' in that specification.
Living Standard 
HTML 5.1
The definition of 'Document readiness' in that specification.
Recommendation 
HTML5
The definition of 'Document readiness' in that specification.
RecommendationInitial specification.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:90 次

字数:5845

最后编辑:8年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文