To run a function when the page is loaded with JavaScript, we run the code in the window.onload
method.
For instance, we write
const init = () => {
alert("hello");
};
window.onload = init;
to set the window.onload
property to the init
function.
window.onload
is called when the page is loaded so we see 'hello'
displayed when it’s loaded.