Skip to main content Accessibility Feedback

A native JavaScript equivalent of jQuery’s .ready() method

Modern web browsers—including IE9 and above—provide an easy way to run scripts once DOM content is fully loaded:

document.addEventListener( 'DOMContentLoaded', function () {
    // Do stuff...
}, false );

However, this isn’t a true analog for jQuery’s $( document ).ready(function() method. If you use addEventListener after the DOM content has already loaded, the event that it’s listening for has already happened, so the event never triggers.

Fortunately, there’s a really easy, lightweight helper method you can use instead:

var ready = function ( fn ) {

    // Sanity check
    if ( typeof fn !== 'function' ) return;

    // If document is already loaded, run method
    if ( document.readyState === 'complete'  ) {
        return fn();
    }

    // Otherwise, wait until document is loaded
    document.addEventListener( 'DOMContentLoaded', fn, false );

};

// Example
ready(function() {
    // Do stuff...
});

This runs immediately if the document is already loaded, and if not, waits until it is.


🚀 Make 2018 the year you master JavaScript! My pocket guides and mini courses are short, focused, and made for beginners. You can do this!

Have any questions or comments about this post? Email me at chris@gomakethings.com or contact me on Twitter at @ChrisFerdinandi.

Get Daily Developer Tips