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
    // The document has finished loading and the document has been parsed but sub-resources such as images, stylesheets and frames are still loading. The state indicates that the DOMContentLoaded event has been fired.
    document.addEventListener( 'interactive', fn, false );

    // Alternative: The document and all sub-resources have finished loading. The state indicates that the load event has been fired.
    // document.addEventListener( 'complete', fn, false );

};

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

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


🚀 I just relaunched my Vanilla JS Pocket Guides with new code examples and real projects to help tie everything you’ll learn together. Check it out.

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