2

I've been looking for a solution that will reload the a page at a specified interval, but only if the server from which that page comes from can deliver the page. Network problems, server problems, etc. should prevent the page from trying to reload. I'm a little surprised that there isn't more of a ready solution, since it seems like this would be the preferred behavior most of the time, instead of loading a blank page with an error message.

I tried to add on to a solution already on stackoverflow:

Javascript: Check if server is online?

but I while it does reload periodically, it doesn't stop trying to reload if the network isn't working (I turn WiFi off to simulate this). I did not try to simulate a server problem.

Here is my non-working version of a periodic reload:

function reloadpage() {
   setTimeout(checkServerStatus, 60000);
}

function checkServerStatus() {
   var img = document.body.appendChild(document.createElement("img"));
   img.onload = function() {
      location.reload(true);
   };
   img.src = "http://some/image.jpg";
}
Community
  • 1
  • 1
Brecky Morris
  • 221
  • 2
  • 8
  • Maybe it happens because of caching. Did you try to add a random parameter to the image url? Something like this ```img.src = "http://some/image.jpg?v=" + (new Date()).getTime();``` – Alexander Popov Mar 18 '16 at 22:31

2 Answers2

2

Try this

function checkPage(interval) {
    interval = interval || 10*60*1000;  // every 10 minutes
    setTimeout(function(){
        $.ajax({ method: 'HEAD', url: 'http://'})
            .done(function(){           // headers retrieved ... it's alive
                location.reload();
            })
            .fail(function(){           // sorry we failed
                checkPage(6000);        // check again but in 1 min
            })
    }, interval);
}

checkPage(5*60*1000);                   // reload in 5 minutes

This will request server headers after interval milliseconds. If they arrive, server is up and we reload. If not we check again in 1 minute.

If you want to guarantee the page is there, change HEAD to GET and check the html returned is what you expect it to be.

Wainage
  • 4,892
  • 3
  • 12
  • 22
1
function reloadpage() {
    $.ajax({
        url: "your url",
        type: "GET",
        complete: function(e, xhr, settings) {
            if (e.status === 200 || e.status == 304) {
                location.reload();
            } else {
                alert("server unreacheable. Do not reload");
            }
        }
    });
    setTimeout(reloadpage, 10000);
}

setTimeout(reloadpage, 10000);
matcheek
  • 4,887
  • 9
  • 42
  • 73
  • This solution seems to work in the case of an internet disconnection (e.g. WiFi gets turned off on laptop client), but does not work when the server is not working (in this case, turning off Tomcat on server). Then it returns a 503 error. I tried to fix this by adding an || e.status == 503 but that didn't change anything. – Brecky Morris Mar 18 '16 at 23:31