Alex Murray Alex Murray - 3 months ago 20
Javascript Question

Running function on first time page load

I'm trying to run a spinner on the first time a user views the homepage on a website. I'm using

localStorage
to see if the user has visited the site before but I don't think it is running correctly.

function load() {
var isFired = localStorage.getItem('checkFired');
if (isFired != '1'){
} else {
$(".se-pre-con").fadeOut("fast");
localStorage.setItem('checkFired', '1');
}
}

$(window).load(function() {
load();
});


This only needs to run the first time the view the homepage. If they navigate away and come back I don't want the spinner to be displayed. Currently it runs everytime they view the homepage. If I put the below code in the
if
part of the
if
statement, the spinner continues to spin and the page never loads.

$(".se-pre-con").fadeOut("fast");
localStorage.setItem('checkFired', '1');


Any ideas how I can get this working?

EDIT: Css of spinner

.se-pre-con {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 9999;
background: url(../img/ring.gif) center no-repeat #fff;
overflow-y: hidden;
}

Answer

You have two choices (both with it's minor problems)

  1. make the spinner CSS visible by default (and handle hide with JS) (like you do already)
  2. make the spinner CSS hidden by default (and handle show with JS)

which one you'll use depends on the amount of elements in the DOM (how fast DOM will be ready for JS to trigger (read LStorage, build the DOM nodes etc...))

Spinner initially display:block;

var firstVisit = localStorage.firstVisit != "1"; // Get & store current state (null/"1")
localStorage.firstVisit = "1";  // Page is now visited so set to "1" regardless

jQuery(function($) {

  var $spinner = $("#spinner"); // Use rather an ID. It's faster!
  $spinner.css({display: firstVisit ? "block" : "none"}); // Hide spin. if not first visit

  if( firstVisit ) {            // First time on page
    $(window).load(function() { // P.S: does not applies to unloaded images and media
      $spinner.fadeOut();       // fade out and display none
    });
  }

});

Spinner initially display:none;

var firstVisit = localStorage.firstVisit != "1"; // Get & store current state (null/"1")
localStorage.firstVisit = "1";        // Page is now visited so set to "1" regardless

jQuery(function($) {

  if( firstVisit ) {                  // First time on page
    var $spinner = $("#spinner");     // Use rather an ID. It's faster!
    $spinner.css({display: "block"}); // Show spinner

    $(window).load(function() { // P.S: does not applies to unloaded images and media
      $spinner.fadeOut();       // fade out and display none
    });
  }
  // else: spinner will be hidden by default (CSS) so all fine

});