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:

Psst... I just launched a new guide to ditching jQuery for vanilla JS. Buy it 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 like Ditching jQuery, my new beginner's guide to vanilla JavaScript. Buy it today →
  • More articles on...
  • Code

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

Get the Weekly Digest