Skip to content

Instantly share code, notes, and snippets.

@danwill
Last active December 11, 2015 23:38
Show Gist options
  • Save danwill/4678038 to your computer and use it in GitHub Desktop.
Save danwill/4678038 to your computer and use it in GitHub Desktop.
Javascript: Detect network connectivity #snippet
<!-- Make sure you add the manifest to your html document -->
<html manifest="myapp.appcache">
CACHE MANIFEST
# application files...
NETWORK:
js/ping.js
MYAPP.network = (function() {
var that = {
isOnline: false,
init: function() {
// These events aren't currently supported by Safari
$(document.body).bind("online", that.checkStatus);
$(document.body).bind("offline", that.checkStatus);
that.checkStatus();
},
/**
* Navigator.onLine isn't a reliable indication of the network status,
* so we try to make a call to a JS file that sits up on the server. Since the
* JS file is specified under the NETWORK header in the appcache document,
* the file won't be cached – forcing a server lookup whenever it's requested
*/
checkStatus: function() {
if (navigator.onLine) {
$.ajax({
async: true,
dataType: 'json',
url: "js/ping.js",
type: "GET",
timeout: 15000,
cache: false,
error: function(req, status, err) {
that.setStatus(false);
},
success: function(data, status, req) {
that.setStatus(true);
}
});
}
else {
that.setStatus(false);
}
},
setStatus: function(isOnline) {
// Do something
that.isOnline = isOnline;
},
getOnlineStatus: function() {
return that.isOnline;
}
};
return that;
}()); //end APP.network
// js/ping.js
{"status":"Online"} // This can be any content
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment