Last active
May 20, 2017 12:01
-
-
Save fchristant/440ea5077db60fff2a14108ce152ca0b to your computer and use it in GitHub Desktop.
SW to redirect users to dedicated offline page when disconnected
This file contains hidden or 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
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