javascript 我如何在文档 readyState 完成时触发事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5968300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:58:37  来源:igfitidea点击:

how do i fire an event when document readyState is complete

javascript

提问by ptamzz

I want to fire and event when the DOM has completely loaded. I checked out document.readyStatebut it's not an event. I want to fire it when the readyStateis complete. How do I do that?

我想在 DOM 完全加载时触发和事件。我签出,document.readyState但它不是一个事件。我想在readyState完成后解雇它。我怎么做?

采纳答案by bstoney

For anyone already using the jQuery library the readyfunction can be used to handle this.

对于已经在使用 jQuery 库的任何人,可以使用ready函数来处理这个问题。

Otherwise the solution from @Neal will achieve the same functionality without needing to add an additional dependency.

否则@Neal 的解决方案将实现相同的功能,而无需添加额外的依赖项。

回答by Naftali aka Neal

Some easy googling point me to this code:

一些简单的谷歌搜索指向我这个代码:

// alternative to DOMContentLoaded
document.onreadystatechange = function () {
    if (document.readyState == "complete") {
        initApplication();
    }
}

And to this link

这个链接

回答by SLaks

Handle the window.loadevent.

处理window.load事件

This will only fire when all external resources (including images) have loaded.

这只会在所有外部资源(包括图像)都加载后触发。

回答by slandau

Taken from another post, however, you could do it like this:

但是,取自另一篇文章,您可以这样做:

var alreadyrunflag = 0; //flag to indicate whether target function has already been run

if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", function() {
    alreadyrunflag = 1;
    // perform what you need to
  }, false);
} else if (document.all && !window.opera) {
  var contentloadtag = document.getElementById("contentloadtag");
  contentloadtag.onreadystatechange = function() {
    if (this.readyState == "complete") {
      alreadyrunflag = 1;
      // perform what you need to
    }
  }
}
//fallback
window.onload = function() {
  setTimeout(function() {
    if (!alreadyrunflag) {
      // perform what you need to
    }
  }, 0);
}

This checks that the DOM is fully loaded, however, if it isn't, it falls back to onload. You can obviously manipulate this though.

这会检查 DOM 是否已完全加载,但是,如果不是,则回退到onload. 不过,您显然可以操纵它。

Also, if JQuery is an option, you can achieve the same effect by using just one simple function:

此外,如果 JQuery 是一个选项,您可以通过使用一个简单的函数来实现相同的效果:

$(document).ready(function() {
  // Handler for .ready() called.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.js"></script>