How to detect if DOMContentLoaded was fired
You can check the document's readyState
value and this way tell if the event was fired or not. Here's the code to run a function named start()
when the document has finished parsing:
if (/complete|interactive|loaded/.test(document.readyState)) {
// In case the document has finished parsing, document's readyState will
// be one of "complete", "interactive" or (non-standard) "loaded".
start();
} else {
// The document is not ready yet, so wait for the DOMContentLoaded event
document.addEventListener('DOMContentLoaded', start, false);
}
Notice that the code above detects when the document has finished parsing. Beware that's not the same as detecting if DOMContentLoaded
was fired (which happens immediately after interactive
), but it serves the same practical purpose, i.e., it tells you that the document has finished loading and has been parsed, but sub-resources such as images, stylesheets and frames are still loading (source).
For seeing if all resources in the page have been loaded:
if (document.readyState === "complete" || document.readyState === "loaded") {
// document is already ready to go
}
This has been supported in IE and webkit for a long time. It was added to Firefox in 3.6. Here's the spec. "loaded"
is for older Safari browsers.
If you want to know when the page has been loaded and parsed, but all subresources have not yet been loaded (which is more akin to DOMContentLoaded
), you can add the "interactive" value:
if (document.readyState === "complete"
|| document.readyState === "loaded"
|| document.readyState === "interactive") {
// document has at least been parsed
}
Beyond this, if you really just want to know when DOMContentLoaded has fired, then you'll have to install an event handler for that (before it fires) and set a flag when it fires.
This MDN documentation is also a really good read about understanding more about the DOM states.