Rohit Bhardwaj
Rohit Bhardwaj

Reputation: 269

Run a function on first time page load not on page refresh in 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?

Upvotes: 6

Views: 4984

Answers (2)

Alberto De Caro
Alberto De Caro

Reputation: 5213

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.

Upvotes: 1

Tommi
Tommi

Reputation: 3247

Since you use asp and check for postback is ok for you, just render client-side flag;

in aspx:

<script type="text/javascript">window.ispostback = <%= Page.IsPostBack %>;</script>

in client script:

if (!window.ispostback) {
   // do stuff
};

Upvotes: 0

Related Questions