Run javascript on document ready (Javascript)

This snippet implements the equivalent of jQuery's $(document).ready() but without the overhead of that library.

It'll trigger the provided callback function when the DOM has loaded (or, immediately if it already has)

Similar To

Details

  • Language: Javascript

Snippet

function doDocumentReady(fn){
    /* $(document).ready() without javascript
    */
    if (document.readyState === "complete" ||
        (document.readyState !== "loading" && !document.documentElement.doScroll)
                                            ) {
            fn();
    } else {
            document.addEventListener("DOMContentLoaded", fn);
    }
}

Usage Example

var callback = function(){
    console.log("dom loaded");
    do_stuf();
}

doDocumentReady(callback);