Reputation: 103
I need some conditional jquery to check internet availability as below and if available it refresh the page and then wait for same amount of time as of refresh and do the same activity again like in while loop
<script>
var a=navigator.onLine;
if(a){
<META HTTP-EQUIV="refresh" CONTENT="10">
}else{
alert('ofline');
}
</script>
Please help regarding above lines of code.
Thank you
Upvotes: 3
Views: 1409
Reputation: 606
One way to check for connectivity would be to set up a small png image or file on your same web server (same domain as current page) and test if you can connect to that file. Setting a timeout on an ajax call will trigger its error handler if no response is received after a number of seconds.
function check_connect()
var testURL = "/somefile.png"
var waitTime = 15000 // recheck every 15 seconds
$.ajax({
type: 'GET',
url: testURL,
timeout: 5000, // allow this many milisecs for network connect to succeed
success: function(data) {
// we have a connection, reload page then try again after waitTime
location.reload(); // reloads entire page
window.setTimeout(check_connect, waitTime) // try again after waitTime miliseconds
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// no connection, try again after waitTime
window.setTimeout(check_connect, waitTime)
}
});
There may be other helpful answers here JQuery Ajax - How to Detect Network Connection error when making Ajax call
And more about jquery's ajax settings such as timeout are here http://api.jquery.com/jquery.ajax/
Upvotes: 4