DEV Community

Discussion on: jQuery $(document).ready() in vanilla JavaScript

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

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

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

I've just updated the gist!