Last active
December 11, 2015 23:38
-
-
Save danwill/4678038 to your computer and use it in GitHub Desktop.
Javascript: Detect network connectivity #snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- Make sure you add the manifest to your html document --> | |
<html manifest="myapp.appcache"> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CACHE MANIFEST | |
# application files... | |
NETWORK: | |
js/ping.js |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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