Run javascript on document ready



Published: 2021-12-30 18:03:13 +0000
Categories: Javascript,

Language

Javascript

Description

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

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

Keywords

javascript, domready, ondomready, domcontentloaded, event,

Latest Posts


Copyright © 2022 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk, http://phecoopwm6x7azx26ctuqcp6673bbqkrqfeoiz2wwk36sady5tqbdpqd.onion and http://snippets.bentasker.i2p
hit counter