DEV Community

Andrea Berardi
Andrea Berardi

Posted on • Originally published at andberry.me

jQuery $(document).ready() in vanilla JavaScript

jQuery's $(document).ready() method allows us to safely run code only once the DOM is loaded and parsed.

Not to be confused with $( window ).on( "load"), to be used if we want to run code only if the whole page content (DOM, and assets as well) is loaded in the browser.

We can achieve the same result with vanilla js and Web APIs, in particular using:

  • Window: DOMContentLoaded event
  • document.readyState

The tricky part is considering that when the browser runs our code it may have already loaded and parsed the DOM, so the best practice is to first check the document.readyState variable.

Here is my complete gist:

Discussion (4)

Collapse
jonrandy profile image
Jon Randy

Is there a reason why you've made the event handler an anonymous function that calls doOnDocumentLoaded instead of just making doOnDocumentLoaded itself the handler?

if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', doOnDocumentLoaded);
} else {
    doOnDocumentLoaded();
}
Enter fullscreen mode Exit fullscreen mode
Collapse
andberry profile image
Andrea Berardi Author

If I got your question, actually I did make doOnDocumentLoaded the event listener.

Basically I need to do the same things twice, on line 2 in case document is still loading, and line 4 if the document is already loaded: this is why I declared the function first and use it as event handler in line 2 and call it in line 4.

Please reply if I'm wrong or I didn't fully understand your question.

Collapse
jonrandy profile image
Jon Randy • Edited

Your event handler isn't doOnDocumentLoaded, rather it is an anonymous function that calls doOnDocumentLoaded - a rather unnecessary step when you could just usedoOnDocumentLoaded directly as the handler as I showed in my example

Thread Thread
andberry profile image
Andrea Berardi Author

And yes, you're totally right!
Sorry, and thank you so much!

I've just updated the gist!