Skip to main content Skip to secondary navigation 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:

Hey there! If you can hack together some jQuery but feel like you don't really know JavaScript, I've written a step-by-step training guide to help you master vanilla JavaScript. Start learning today →
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.

If you liked this article, you might also enjoy Ditching jQuery, a step-by-step training guide to help you master vanilla JavaScript. Start learning today →

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

Get the Spare Parts Newsletter

Every week, I send out a short email packed with web development resources and interesting stuff from around the web.