Skip to content

Instantly share code, notes, and snippets.

@fchristant
Last active May 20, 2017 12:01
Show Gist options
  • Save fchristant/440ea5077db60fff2a14108ce152ca0b to your computer and use it in GitHub Desktop.
Save fchristant/440ea5077db60fff2a14108ce152ca0b to your computer and use it in GitHub Desktop.
SW to redirect users to dedicated offline page when disconnected
const OFFLINE_URL = '/offline';
self.addEventListener('install', function(e) {
e.waitUntil(
caches.open('jungledragon').then(function(cache) {
return cache.addAll([
OFFLINE_URL, '/'
]);
})
);
});
self.addEventListener('fetch', event => {
// only listen to requests for HTML pages, ignore all other network requests
if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
// if the HTML fetch fails, forcefully redirect users to the cached offline page
event.respondWith(
fetch(event.request).catch(error => {
return caches.match(OFFLINE_URL);
})
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment