Skip to content Skip to sidebar Skip to footer

How To Distinguish Between The First Page Load And The Consecutive Page Refresh Events In Javascript?

Hi I need to distinguish between 2 events, When the page loads for the first time, I want to set some value in the header say 'Welcome' Later if after loading if the user refreshe

Solution 1:

As this answer states, you can use cookies. When the page is refreshed, this function will check if the cookie exists or not. If it doesn't, the function will set a cookie. If the cookie does exist, then the function will alert "You refreshed!".

function checkFirstVisit() {
  if(document.cookie.indexOf('mycookie')==-1) {
    // cookie doesn't exist, create it now
    document.cookie = 'mycookie=1';
  }
  else {
    // not first visit, so alert
    alert('You refreshed!');
  }
}

and in your body tag, put:

<body onload="checkFirstVisit()">

EDIT: To make sure that if a user leaves the page and then re-enters it without closing and opening the browser in between, you can use some onunload event to clear the cookie.


Solution 2:

If you don't have to support old browsers, I suggest to use localStorage:

if (localStorage.getItem("visit") == null)
{
    // Show Welcome message
    $('body').append("<h1>Welcome, guest!</h1>");
}

localStorage.setItem("visit", new Date());
// Here you can check if last visit date is longer than a day and clear it up, showing Welcome message again...

Fiddle.

Can I use Web Storage?


Post a Comment for "How To Distinguish Between The First Page Load And The Consecutive Page Refresh Events In Javascript?"