简体   繁体   中英

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?

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 .

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
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM