how to refresh page using javascript if connected?

javascript, jquery, page-refresh

Solution

You can use `navigator.onLine` to detect a network connection

setInterval(function() {
    if (navigator.onLine) {
        location.reload();
    }
}, 120000); /* 120000 ~> 2 minutes */

otherwise, you may use instead an `HEAD` ajax request to a same-domain resource and refresh the page only if the response return a `200/304` status, e.g.

setInterval(function() {

    $.ajax({ 
        url  : "/favicon.ico", /* or other resource */
        type : "HEAD"
    })
    .done(function() {
        location.reload();
    });
}, 120000); /* 120000 ~> 2 minutes */

Problem

I have a web page that i want it to refresh every 2 minutes, using the following code: ``` location.reload(); ``` The problem is that I assume that the user is connected; but if it happened that s/he is not connected online the page will fail and give the default browser(no connection error page ); and the page will never refresh except manually by the user can i include a ping mechanism to decide weather to refresh or not?

Original source