Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load page only once

Tags:

javascript

Below is my code but page load continuously,i want to load only once

 window.onload = function () {
            window.location.reload();
        }
like image 628
Ghanshyam Lakhani Avatar asked Nov 30 '25 12:11

Ghanshyam Lakhani


2 Answers

$(document).ready(function(){    
    if(document.URL.indexOf("#")==-1){ //Check if the current URL contains '#'
        url = document.URL+"#"; // use "#". Add hash to URL
        location = "#";
        location.reload(true); //Reload the page
    }
});

Due to the if condition page will reload only once.

The other way to achieve this is :

(function()
{
  if( window.localStorage )
  {
    if( !localStorage.getItem('firstLoad') )
    {
      localStorage['firstLoad'] = true;
      window.location.reload();
    }  
    else
      localStorage.removeItem('firstLoad');
  }
})();
like image 200
Kurenai Kunai Avatar answered Dec 02 '25 02:12

Kurenai Kunai


There are a few ways you could solve this, all of which require saving state across page loads. You could use cookies, localStorage, the location object itself, etc.

Here's a way that checks to see if there is a hash string 'reloaded' and, if not, adds it and reloads the page. Then, when it tries to execute again, the hash will be there and it will not reload:

if (location.hash.indexOf('reloaded') === -1) {
  location.hash += 'reloaded';
  location.reload();
}
like image 34
rgthree Avatar answered Dec 02 '25 03:12

rgthree



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!