Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Feature detect support for DOMContentLoaded event

Is it possible to detect support for the DOMContentLoaded event?

Method's like Kangax's solution here won't work because DOMContentLoaded is not exposed as a property of any element: Detecting event support without browser sniffing

like image 475
Web_Designer Avatar asked Aug 07 '13 03:08

Web_Designer


People also ask

What is the requirement of the DOMContentLoaded event listener?

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A different event, load , should be used only to detect a fully-loaded page.

How do you test for DOMContentLoaded?

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; ... }

What is the difference between document load event and document DOMContentLoaded event?

The DOMContentLoaded event fires when parsing of the current page is complete; the load event fires when all files have finished loading from all resources, including ads and images.

Does DOMContentLoaded wait for scripts?

DOMContentLoaded and styles External style sheets don't affect DOM, so DOMContentLoaded does not wait for them. The reason for this is that the script may want to get coordinates and other style-dependent properties of elements, like in the example above.


1 Answers

Just listen for all three events and the first one triggered wins. If the winner is DOMContentLoaded, it's supported. If it hasn't been triggered by the time one of the other two has been triggered, then it's not supported.

<script>
    var hasDOMContentLoaded = false,
        ready = false,
        readyMethod = null;

    // Listen for "DOMContentLoaded"
    document.addEventListener("DOMContentLoaded", function(event) {
        hasDOMContentLoaded = true;
        init("DOMContentLoaded");
    });

    // Listen for "onreadystatechange"
    document.onreadystatechange = function () { init("onreadystatechange"); }

    // Listen for "load"
    document.addEventListener("load", function(event) { init("load"); });

    // Gets called after any one of the above is triggered. 
    function init(method) {
        if(!ready) {
            ready = true;
            readyMethod = method;
            go();
        }
    }

    // Page is ready, time is up. 
    // Eitehr DOMContentLoaded has been triggered or it never will.
    function go() {
        console.log("hasDOMContentLoaded: ", hasDOMContentLoaded);
        // My initialization code here
    }

</script>
like image 71
TxRegex Avatar answered Oct 27 '22 14:10

TxRegex