问题描述:

I want my website page to reload once when it has already opened for the first time. I wrote this function in my javascript file for that...

var i;

$(document).ready(function(){

for ( i=0;i<1;i++){

if(i===0){

location.reload();

break;

}

}

});

But the page keeps reloading again and again as if the above function was a recursive one.

How do I do this?

P.S I'm doing it because of this issue.

网友答案:
<script type='text/javascript'>
  (function() {
    if( window.localStorage ) { 
      if( !localStorage.getItem('firstLoad') ) { 
        localStorage['firstLoad'] = true;
        window.location.reload(); 
      } else 
        localStorage.removeItem('firstLoad'); 
    } 
  })();
</script>
网友答案:

Here is what's happening:

  • The page loads for the first time, jQuery calls any handlers on the document.ready event

  • The page reloads

  • The document.ready call is made again

  • repeat

Out of curiosity, why would you want to do that? And why do you have a for loop that will run for one iteration?


Also, to answer your question as far as I know the only way to make sure the page doesn't reload is use a cookie that lasts for about 5 seconds. Then, on document.ready check for that cookie and if it exists then don't reload.

网友答案:

You must either set a cookie (or use javascript's localStorage), or use xhr to retrieve a value held on a remote server.

If you want to use cookies, it's as simple as

document.cookie = "username=John Doe";

where the document.cookie is a query string of the form (x=y;a=b;n=z)

If you want the page to reload every time the user vists, be sure to unset the cookie once you've done any necessary processing when a page reload has been set.

网友答案:
$( window ).load(function() {
    if (window.location.href.indexOf('reload')==-1) {
         window.location.replace(window.location.href+'?reload');
    }
});
网友答案:

Yours code executed each time $(document).ready(), so it's not surprise that your loop is infinity - each load finished as ready state.

If you give more detailed requirements we can solve it with no using window object as data holder. It's bad way but you can set it for test.

Window object stores variables not depend on reload because it's higher then document.

Let's try:

if( window.firstLoad == undefined  ){
    // yours code without any loop
    // plus:
    window.firstLoad = false;
}

You can make it with localStorage API.

Check this link also, it's giving more information about window object variables: Storing a variable in the JavaScript 'window' object is a proper way to use that object?

相关阅读:
Top