Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a function on first time page load not on page refresh in javascript

Tags:

javascript

I would like a function to be executed only on the first page load and not when page is refreshed.

For example, it should not execute when the user clicks on the submit button, or on other page refresh.

I can avoid it in .net by using the ispostback property, but how can I do this in JavaScript?

like image 605
Rohit Bhardwaj Avatar asked Apr 15 '13 10:04

Rohit Bhardwaj


People also ask

How to one-time page refresh after the first page load automatically?

We will discuss multiple ways to One-time page refresh after the first-page load automatically using Javascript or JQuery. Javascript can be very useful for Frontend and Backend Development, The one language to rule them all, as they say.

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. window.onload = () => { if (localStorage.getItem ("hasCodeRunBefore")) { return } console.log ('hello') localStorage.setItem ("hasCodeRunBefore", true); }

What does the onload property do in JavaScript?

The onload property processes load events after the element has finished loading. This is used with the window element to execute a script after the webpage has completely loaded. The function that is required to be executed is assigned as the handler function to this property. It will run the function as soon as the webpage has been loaded.

How to execute a script after the webpage has finished loading?

Method 1: Using onload method: The body of a webpage contains the actual content that is to be displayed. The onload event occurs whenever the element has finished loading. This can be used with the body element to execute a script after the webpage has completely loaded.


1 Answers

So you want to catch only the first page view. It is also known as unique page view. And then there are the page views, that are incremented at each page reload.

The first one should be tracked managing the session of the visit (for example using a cookie). The first time the page is visited, a cookie is set and the counter incremented. If the page is visited again if the cookie is already set the counter will not be incremented. Unless the cookies have been deleted and the user has changed the browser.

The second one will be incremented over and over again at each page refresh. Easly achived via javascript. To manage programmatically the page refresh status, I suggest you this answer. To manage dynamically the execution of a script, I suggest you the ClientScriptManager.

like image 98
Alberto De Caro Avatar answered Oct 03 '22 12:10

Alberto De Caro