jQuery has a built-in method named ready() to fire once the document is loaded successfully. We can achieve the same without jQuery too. Here, I shared some methods to trigger events when the page is loaded using vanilla JavaScript. It is the same as document ready method in jQuery.
3 Methods for Document Ready Vanilla JavaScript
1. Using addEventListener Method for Document Ready Without jQuery
We can use the addEventListener() method to call your methods once the HTML page is loaded successfully.
document.addEventListener("DOMContentLoaded", function () {
console.log("page is loaded");
});
2. Using onreadystatechange
This method is similar to the above method but works slightly differently.
document.onreadystatechange = function () {
if (document.readyState == "interactive") {
console.log("page is loaded");
}
}
3. Using Custom Function
We can combine the above two methods to create a function that we will be called once the application is loaded.
function domReady(e) {
document.addEventListener("DOMContentLoaded", e);
if (document.readyState === "interactive" || document.readyState === "complete") {
e();
}
}
domReady(() => console.log("HTML is loaded successfully"));