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);
}
}
Mozila Firefox says that
onreadystatechange
is an alternative toDOMContentLoaded
.In
DOMContentLoaded
the Mozila's doc says:I think
load
event should be used for a full document+resources loading.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
:This is also how jQuery does it.
Depending on where the JavaScript is loaded, this can be done inside an interval:
In fact,
document.readyState
can have three states: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 fordocument.readyState === "complete"
.