Sometimes, we may want to run code when the DOM is loaded without using jQuery.
Therefore, we need to find an equivalent of jQuery’s $(document).ready in plain JavaScript.
In this article, we’ll look at how to find the equivalent of jQuery’s $(document).ready in plain JavaScript.
Equivalent of jQuery’s $(document).ready in Plain JavaScript
To find the equivalent of jQuery’s $(document).ready in plain JavaScript, we can listen to the DOMContentLoaded event on the document object with the addEventListener method.
To do this, we write:
document.addEventListener("DOMContentLoaded", (event) => {
console.log('document ready')
});
to listen to the DOMContentLoaded event on document .
We call document.addEventListener with an event handler callback as the 2nd argument that runs when the DOM is successfully loaded.
Therefore, when the page is loaded, we should see 'document ready' logged.
Conclusion
To find the equivalent of jQuery’s $(document).ready in plain JavaScript, we can listen to the DOMContentLoaded event on the document object with the addEventListener method.