Skip to content

Instantly share code, notes, and snippets.

@oroce
Created November 23, 2011 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oroce/1390109 to your computer and use it in GitHub Desktop.
Save oroce/1390109 to your computer and use it in GitHub Desktop.
ideas to check browser is online
/*
@dependencies
jQuery
*/
(function( window, $, undefined ){
var support = {
onLine: undefined === typeof window.navigator.onLine,
applicationCache: !!window.applicationCache
},
app = {
eventOnline: function(){
if( support.onLine ){
if( window.navigator.onLine === false ){
//we are okay, browser is offline
$( document )
.removeClass( "online" )
.addClass( "offline" );
}
else if( window.navigator.onLine === true ){
//in chrome 15 onLine === true if computer is connected to the internet
//in ff, onLine === false if browser is set to work offline, otherwise it's true
//so if browser supports applicationCache
if( support.applicationCache ){
//if browser support appCache, we
//just update it and listening for events
window.applicationCache.update();
}
else{
app.fallbackAjax();
}
}
}
},
appCacheReady:function(){
//we don't give a fuck, whether appCache can be updated,
//we are just happy, because browser is online
$( document )
.removeClass( "offline appcache-error" )
.addClass( "online appcache-success" );
},
appCacheError: function(){
$( document )
.removeClass( "online appcache-success" )
.addClass( "appcache-error" );
},
fallbackAjax: function(){
$.ajax({
url: "appcache.manifest",
success: function(){
$( document )
.removeClass( "offline" )
.addClass( "online" );
},
error: function(){
$( document )
.removeClass( "online" )
.addClass( "offline" );
},
complete: function(){
_interval = setTimeout( app.fallbackAjax );
}
});
}
}, _interval;
$( window )
.on( "online.connected offline.connected", app.eventOnline )
.trigger( "online.connected" );
if( support.applicationCache ){
$( window.applicationCache )
.bind( "updateready", app.appCacheReady )
.bind( "error", app.appCacheError );
}
})( window, jQuery );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment