I\'m trying to help developing a library and for it I\'m trying to work with page loading.
In the process I want to make the library completely compatible with the use o
If you need to wait for the HTML document to be fully loaded and parsed to run something, you need to wait for DOMContentLoaded, no doubt about it. But if you can't control when your script is going to execute, it's possible that DOMContentLoaded was already fired by the time you get a chance to listen for the event.
To take that into consideration, your code needs to check if DOMContentLoaded was already fired and, if so, proceed to executing right away whatever it is that needed to wait for DOMContentLoaded:
function runWhenPageIsFullyParsed() {
// your logic goes here
}
if (document.readyState === "complete") {
// already fired, so run logic right away
runWhenPageIsFullyParsed();
} else {
// not fired yet, so let's listen for the event
window.addEventListener("DOMContentLoaded", runWhenPageIsFullyParsed);
}
The correct order of events during page loading is:
document.readyState changes to interactivewindow's DOMContentLoaded event gets fireddocument.readyState changes to completewindow's load event gets fired loadYou can check the complete order of events during page loading in this fiddle.