How to detect if DOMContentLoaded was fired

前端 未结 6 1958
误落风尘
误落风尘 2020-12-02 14:00

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

6条回答
  •  甜味超标
    2020-12-02 14:54

    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 during page loading is:

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

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

提交回复
热议问题