Sometimes, we want to execute function after complete page load with JavaScript.
In this article, we’ll look at how to execute function after complete page load with JavaScript.
How to execute function after complete page load with JavaScript?
To execute function after complete page load with JavaScript, we listen to the readystatechange
event.
For instance, we write
document.addEventListener("readystatechange", (event) => {
if (event.target.readyState === "interactive") {
console.log("hi");
}
if (event.target.readyState === "complete") {
console.log("hi 2");
}
});
to listen to the document
‘s readystatechange
event with addEventListener
.
In the event listener callback, we get the document
‘s readyState
with event.target.readyState
.
If it’s 'interactive'
then the page can be interacted with but it’s still loading.
And if the readyState
is 'complete'
, then the page is completely loaded.
Conclusion
To execute function after complete page load with JavaScript, we listen to the readystatechange
event.