Categories
JavaScript Answers

How to execute a JavaScript function on the first page load?

Spread the love

Sometimes, we want to execute a JavaScript function on the first page load.

In this article, we’ll look at how to execute a JavaScript function on the first page load.

How to execute a JavaScript function on the first page load?

To execute a JavaScript function on the first page load, we can set a flag in local storage is done.

Then we stop running the function on subsequent page loads if the flag exists.

For instance, we write:

window.onload = () => {
  if (localStorage.getItem("hasCodeRunBefore")) {
    return
  }
  console.log('hello')
  localStorage.setItem("hasCodeRunBefore", true);
}

to set window.onload to a function that checks if the local storage with key 'hasCodeRunBefor' exists.

If it doesn’t, then we run the console log and calls localStorage.setItem to set the 'hasCodeRunBefore' flag to true.

Conclusion

To execute a JavaScript function on the first page load, we can set a flag in local storage is done.

Then we stop running the function on subsequent page loads if the flag exists.

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 *