Dewsworld
Dewsworld

Reputation: 14033

jQuery differentiate between page load and refresh

I need to differentiate between page load and page refresh in jQuery. I have no idea how to implement the following code.

if( /* this page is loaded reffered */ )
    ++count ;
else if( /* this paged is refreshed */ )
    alert("refreshed");

Upvotes: 1

Views: 1357

Answers (2)

fncomp
fncomp

Reputation: 6188

You could use the hash to implement this:

var loc = window.location,
    isLoad = false;
if (String(loc.hash).indexOf('loaded') === -1) {
    loc.hash += 'loaded';
    isLoad = true;
}

Then just check isLoad to see if it's a refresh or not.

Upvotes: 1

Juri
Juri

Reputation: 32900

Using a simple counter won't work. I'll try to illustrate it in semi-pseudo-code

$(document).ready(function(){
  if(isPageLoadCookiePresent){
     //this is a page load
     setPageLoadCookie();
  }else{
     //this is a page refresh
  } 
});

Alternatively, instead of setting a cookie, you could use the HTML5 web storage API.

saveButton.addEventListener('click', function () {
  window.localStorage.setItem('value', area.value);
  window.localStorage.setItem('timestamp', (new Date()).getTime());
}, false);
textarea.value = window.localStorage.getItem('value');

Taken from here

Upvotes: 3

Related Questions