Javascript - 如何检测文档是否已加载(IE 7 / Firefox 3) [英] Javascript - How to detect if document has loaded (IE 7/Firefox 3)
问题描述
我想在文档加载后调用函数,但文档可能已经或可能尚未完成加载。如果它加载了,那么我可以调用该函数。如果它没有加载,那么我可以附加一个事件监听器。我无法在onload已经触发后添加一个eventlistener,因为它不会被调用。那么如何检查文档是否已加载?我尝试了下面的代码,但它并不完全有用。有什么想法?
I want to call a function after a document loads, but the document may or may not have finished loading yet. If it did load, then I can just call the function. If it did NOT load, then I can attach an event listener. I can't add an eventlistener after onload has already fired since it won't get called. So how can I check if the document has loaded? I tried the code below but it doesn't entirely work. Any ideas?
var body = document.getElementsByTagName('BODY')[0];
// CONDITION DOES NOT WORK
if (body && body.readyState == 'loaded') {
DoStuffFunction();
} else {
// CODE BELOW WORKS
if (window.addEventListener) {
window.addEventListener('load', DoStuffFunction, false);
} else {
window.attachEvent('onload', DoStuffFunction);
}
}
推荐答案
这里有不需要galambalazs提到的所有代码。在纯JavaScript中执行此操作的跨浏览器方式只是测试 document.readyState
:
There's no need for all the code mentioned by galambalazs. The cross-browser way to do it in pure JavaScript is simply to test document.readyState
:
if (document.readyState === "complete") { init(); }
这也是jQuery的用法。
This is also how jQuery does it.
根据JavaScript的加载位置,可以在一个区间内完成:
Depending on where the JavaScript is loaded, this can be done inside an interval:
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
clearInterval(readyStateCheckInterval);
init();
}
}, 10);
事实上, document.readyState
可以有三种状态:
In fact, document.readyState
can have three states:
在文档加载时返回loading,一旦完成解析但仍在加载子资源时返回interactive一旦加载就完成。
- 在Mozilla开发者网络上 document.readyState
因此,如果您只需要准备好DOM,请检查 document.readyState ===interactive
。如果您需要准备好整个页面,包括图像,请检查 document.readyState ===complete
。
So if you only need the DOM to be ready, check for document.readyState === "interactive"
. If you need the whole page to be ready, including images, check for document.readyState === "complete"
.
这篇关于Javascript - 如何检测文档是否已加载(IE 7 / Firefox 3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!