Reputation: 791
I want to reload a page only 1 time when the user goes to that page.
I am using the following script:
$(document).ready(function() {
for (i = 1 ; i <= 1 ; i++) {
location.reload();
}
});
But it keeps on reloading the page. Any error with the for loop?
Upvotes: 0
Views: 73
Reputation: 6136
As others have mentioned, you'll need some mechanism of maintaining some kind of flag to indicate that the page has been reloaded that persists after reloading.
Common solutions to this would be cookies, url fragments, local storage.
Cookie
if(!(/\breloaded=1/.test(document.cookie))){
document.cookie = 'reloaded=1';
location.reload();
}
URL fragment
if(location.hash != '#reloaded'){
location.hash = '#reloaded';
location.reload();
}
Local Storage
if (localStorage.getItem('reloaded') != false) {
localStorage.setItem('reloaded', false);
location.reload();
}
Upvotes: 1
Reputation: 18891
JavaScript resets every time the page is loaded. Once the page is reloaded, your for
loop is history. Here's an alternative using HTML5 Local Storage:
$(document).ready(function() {
if(localStorage.getItem('reload') != false)
localStorage.setItem('reload', false);
location.reload();
}
});
Upvotes: 3
Reputation: 156
You can set a cookie to be set using jquery when you first load the page and then use an if statement to run the reload if the page hasn't already been reloaded (which will be defined in the cookie) and delete the cookie after.
Upvotes: -1
Reputation: 193311
You need somehow make page remember that it's has already been loaded before. I would use localStorage/sessionStorage:
$(document).ready(function() {
if (!localStorage.reloaded) {
location.reload();
localStorage.reloaded = true;
}
});
Upvotes: 2