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
how do i fire an event when document readyState is complete
提问by ptamzz
I want to fire and event when the DOM has completely loaded. I checked out document.readyState
but it's not an event. I want to fire it when the readyState
is complete. How do I do that?
我想在 DOM 完全加载时触发和事件。我签出,document.readyState
但它不是一个事件。我想在readyState
完成后解雇它。我怎么做?
采纳答案by bstoney
回答by Naftali aka Neal
回答by SLaks
Handle the window.load
event.
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>