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:
Top comments (4)
Is there a reason why you've made the event handler an anonymous function that calls
doOnDocumentLoaded
instead of just makingdoOnDocumentLoaded
itself the handler?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.
Your event handler isn't
doOnDocumentLoaded
, rather it is an anonymous function that callsdoOnDocumentLoaded
- a rather unnecessary step when you could just usedoOnDocumentLoaded
directly as the handler as I showed in my exampleAnd yes, you're totally right!
Sorry, and thank you so much!
I've just updated the gist!