Reputation: 221
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";
}
Upvotes: 2
Views: 188
Reputation: 5147
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);
Upvotes: 1
Reputation: 5412
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.
Upvotes: 2