Skip to content

jQuery document.ready in Vanilla JavaScript

Using vanilla JavaScript with no jQuery, the simplest way to check if the document is ‘ready’ to be manipulated is using the DOMContentLoaded event:

document.addEventListener('DOMContentLoaded', function () {
  // do something here ...
}, false);
Code language: JavaScript (javascript)

You can also use a named function instead of an anonymous function:

document.addEventListener('DOMContentLoaded', doSomething, false);

function doSomething () {
  // code here...
}
Code language: JavaScript (javascript)

The vanilla JavaScript DOMContentLoaded event is fired when the DOM is ready, but there could still be resources that are being loaded (e.g. images, external stylesheets, etc). If you want to instead start manipulating elements when the full page has loaded, you can use the load event. But note that this event needs to attach the event to the window instead of the document (the document doesn’t have a load event):

window.addEventListener('load', function () {
  // do something here ...
}, false);
Code language: JavaScript (javascript)

One of the above should suffice to allow you to do a jQuery-like $(document).ready() in all modern browsers with plain JavaScript. But if you want support going back to old browsers, including IE9, you can use the following:

function ready(fn) {
  if (document.readyState !== 'loading'){
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

ready(function () {
  // do something here...
});
Code language: JavaScript (javascript)

Finally, if you want even older browser support, including IE8 and below, you would need to do something like this (which also works in modern browsers):

document.onreadystatechange = function () {
  if (document.readyState === "interactive") {
    // do something here...
  }
};
Code language: JavaScript (javascript)
Note: To the best of our knowledge, the information above and the snippet are accurate and up to date. However, in case you notice something wrong, please report snippet or leave a comment below.
View all Snippets
Louis Lazaris
Share:

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

Or start the conversation in our Facebook group for WordPress professionals. Find answers, share tips, and get help from other WordPress experts. Join now (it’s free)!