Categories
JavaScript Answers

How to run a function when the page is loaded with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *