Javascript - 如何检测文档是否已加载 (IE 7/Firefox 3) [英] Javascript - How to detect if document has loaded (IE 7/Firefox 3)
问题描述
我想在文档加载后调用一个函数,但文档可能还没有完成加载.如果它确实加载了,那么我可以调用该函数.如果它没有加载,那么我可以附加一个事件侦听器.我无法在 onload 已经触发后添加事件侦听器,因为它不会被调用.那么如何检查文档是否已加载?我尝试了下面的代码,但它并不完全有效.有什么想法吗?
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
可以有三种状态:
在加载文档时返回正在加载",在完成解析但仍在加载子资源后返回交互",并在加载后返回完成".-- Mozilla 开发者网络上的 document.readyState
Returns "loading" while the document is loading, "interactive" once it is finished parsing but still loading sub-resources, and "complete" once it has loaded. -- document.readyState at Mozilla Developer Network
因此,如果您只需要准备好 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屋!