I’m testing HTML5 offline application. To do that, I’m stopping my local web server (IIS) and open application. It’s loaded fine, but it failed as soon as it request server side API method.
I want to prevent that and instead of $.get(‘/api/method’) read data from my local storage. But I can found any facility to understand my application is offline.
if (/* online */) {
// fire ajax
} else {
// ask localstorage
}
I tried to use navigation.onLine but it seems to be always true (at least I can see that in Chrome).
Do you have any suggestions?
EDIT: taking into account current answers. Application is clearly understand that it’s offline, since it takes resources according to cache.manifest. It’s ridiculous to me, that client need to do any kind of tricks and pings. I assume there should be a easy way to check current mode.
One easy way to check is to add a fallback section in your manifest like this:
Then in
online.jsyou set a global variable to true, inoffline.jsyou set it to false and you just requestonline.jsby Ajax whenever you plan to do some networking and do whatever processing you need conditionally in the callback. In the meantime, maintain all your app data client side.An alternative approach is a blocking polyfill for
navigator.onLineas suggested by Remy Sharp.