How to detect if DOMContentLoaded was fired
Asked Answered
C

6

80

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 of defer and async.

What I want is simple:
How can I know that DOMContentLoaded was fired by the time the file is executed?

Why is this so difficult?
In IE, document.readyState show interactive before DOMContentLoaded.
I won't use browser detection in any way, it's against the policy of me and the rest of the participants.

What's the correct alternative?

Edit:

Seems like I wasn't clear enough. I'm not interested to know if the load event has already occurred!!! I already knew how to solve that problem! I want to know how to solve with DOMContentLoaded!!!

Chess answered 26/2, 2012 at 22:33 Comment(3)
Set a listener that sets a property or variable. If it's set, the event has been dispatched. Of course you might be in a browser that doesn't support the event, in which case it will never occur.Puerility
@Puerility I already had the answer for the browsers the ado not support DOMContentLoaded. For those, I use the load event and the onload event. I still don't have the answer for the question I madeChess
There is no "onload" event, there is an onload attribute/property for setting listeners for the load event. If you want to know unequivocally if DOMContentLoaded has occurred, set a listener and see if it's been called.Puerility
G
85

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.

Greensward answered 26/2, 2012 at 22:45 Comment(8)
You are not answering the question. I want to know about DOMContentLoaded event, not load event. The load event is easy, the DOMContentLoaded I don't know.Chess
@Chess - then install a handler for the DOMContentLoaded event and set a flag when it fires. I don't think there's another option.Greensward
If you want to include when the document has been parsed, but sub-resources are still loading, you can check for "interactive" too. See the second example I added to my answer.Greensward
just adding spice to this discussion ablogaboutcode.com/2011/06/14/…Riptide
The first code snippet is incorrect - document.readyState == "interactive" can also indicate that DOMContentLoaded was fired. See here: developer.mozilla.org/en-US/docs/Web/API/Document/readyStateHexosan
@Greensward it doesn't work for google docs, any idea why?Xanthine
@Xanthine - Please write your own question and show your specific code and your specific situation.Greensward
I did it here (it uses your code) #70323061Xanthine
I
28

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).

Imponderabilia answered 14/3, 2016 at 20:3 Comment(6)
This is not correct. DOMContentLoaded is fired only after interactive (proof here: jsfiddle.net/luciopaiva/grs82byv/20)Mudslinging
@LucioPaiva thanks and you're right - but it only mean that the comment about DCL already fired is incorrect. the code still works perfectly in all cases, so why -1?Imponderabilia
You are right, I was misguided by the comment there. I edited your answer fixing it and adding a bit more info; please let me know what you think.Mudslinging
“A more readable regexp would be […]” → Given the choice, you should always prefer the more readable version of the same code.Denaedenarius
@DenilsonSáMaia i agree. changed it.Imponderabilia
@Imponderabilia Any idea why it doesn't work for google docs?Xanthine
M
19

How to correctly run something on DOMContentLoaded (or ASAP)

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 is:

  • document.readyState starts with loading
  • document.readyState changes to interactive
  • window's DOMContentLoaded event gets fired
  • document.readyState changes to complete
  • window's load event gets fired load

Reference: MDN

You can check the complete order of events during page loading in this fiddle.

Mudslinging answered 6/12, 2019 at 21:12 Comment(5)
Adding log(document.readyState); at the beginning of the JS in your fiddle helps to point out the loading state of document.readyState which occurs before interactive. I would add that important step to the order of events. Outlined on this MDN readyState article. Thanks!Fissiparous
I tried the above solution and there was still few times where my code won't run. So I ended up adding document.readyState === "interactive" condition to my code.Coralloid
@KingHolly I've updated the answer with your suggestion, thanks.Mudslinging
@SaurabhGupta that is interesting. Can you show some code that reproduces the problem? I tried re-running the code in my fiddle above, but it works every time.Mudslinging
@LucioPaiva I am running it inside $.ajax.done method. Also, this code in running in an OSGI container where my code is installed into it (Atlassian plugin). So the load order is not controlled by me and there are lot of different items which are being loaded at the same time.Coralloid
I
1

Try this or look at this link

<script>
    function addListener(obj, eventName, listener) { //function to add event
        if (obj.addEventListener) {
            obj.addEventListener(eventName, listener, false);
        } else {
            obj.attachEvent("on" + eventName, listener);
        }
    }

    addListener(document, "DOMContentLoaded", finishedDCL); //add event DOMContentLoaded

    function finishedDCL() {
        alert("Now DOMContentLoaded is complete!");
    }
</script>

Note

If you have a <script> after a <link rel="stylesheet" ...>

the page will not finish parsing - and DOMContentLoaded will not fire - until the stylesheet is loaded

Iyar answered 27/2, 2012 at 6:49 Comment(1)
Nice try but that does not go after what I'm really after. That does not check if the event had already been fired, that only checks if the event is being fired. I know how to check if the event is being fired but I don't know how to check if the event had already been firedChess
T
0

If you want to know "exactly" if DOMContentLoaded was fired, you could use a boolean flag like this:

var loaded=false;
document.addEventListener('DOMContentLoaded',function(){
loaded=true;
...
}

then check with:

if(loaded) ...
Tomb answered 20/3, 2014 at 19:52 Comment(2)
Nice try :). That is not really an answer, though. As I want it to work correctly with all (major) browsers and with async and defer, I can't be so sure that that will work as expected due to IE.Chess
IE is not a browser :DTomb
R
-7

Here is the thing, if some other library (such as jQuery) already used DOMContentLoaded, you can't use it again. That can be bad news, because you end up without being able to use it. You are gonna say, why not just use $(document).ready(), because, NO!, not everything needs to use jQuery, specially if it is a different library.

Reamy answered 19/8, 2016 at 21:22 Comment(1)
It's not true that you can not have multiple event listeners. Please read up on developer.mozilla.org/en-US/docs/DOM/document.addEventListener and the Publish/Subscribe (pub sub) pattern: msdn.microsoft.com/en-us/library/ff649664.aspxTurenne

© 2022 - 2024 — McMap. All rights reserved.