Sometimes, we want to make the browser wait to display the page until it’s fully loaded with JavaScript.
In this article, we’ll look at how to make the browser wait to display the page until it’s fully loaded with JavaScript.
How to make the browser wait to display the page until it’s fully loaded with JavaScript?
To make the browser wait to display the page until it’s fully loaded with JavaScript, we run our code in the window.onload
method.
For instance, we write
body {
opacity: 0;
}
to set the body element to have opacity 0 initially.
Then we write
window.onload = () => {
setTimeout(() => {
document.body.style.opacity = "100";
}, 500);
};
to set window.onload
to a function that calls setTimeout
with a callback that sets the body’s opacity to 100 after 500 milliseconds.
Conclusion
To make the browser wait to display the page until it’s fully loaded with JavaScript, we run our code in the window.onload
method.