Skip to content

Instantly share code, notes, and snippets.

@deanhume
Last active February 14, 2016 20:39
Show Gist options
  • Save deanhume/5198f12946c29362a3ec to your computer and use it in GitHub Desktop.
Save deanhume/5198f12946c29362a3ec to your computer and use it in GitHub Desktop.
Return an offline page using Service Worker
this.addEventListener('fetch', event => {
// request.mode = navigate isn't supported in all browsers
// so include a check for Accept: text/html header.
if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
event.respondWith(
fetch(event.request.url).catch(error => {
// Return the offline page
return caches.match(offlineUrl);
})
);
}
else{
// Respond with everything else if we can
event.respondWith(caches.match(event.request)
.then(function (response) {
return response || fetch(event.request);
})
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment