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
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: