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?
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.
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); }
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With