Skip to content

Instantly share code, notes, and snippets.

@deanhume
Created August 2, 2016 09:14
Show Gist options
  • Save deanhume/3121e51db8727b6cf213c8446e86bb08 to your computer and use it in GitHub Desktop.
Save deanhume/3121e51db8727b6cf213c8446e86bb08 to your computer and use it in GitHub Desktop.
Offline SW example
function getFilenameFromUrl(path){
path = path.substring(path.lastIndexOf("/")+ 1);
return (path.match(/[^.]+(\.[^?#]+)?/) || [])[0];
}
this.addEventListener('fetch', event => {
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 => {
var cachedFile = getFilenameFromUrl(event.request.url);
// Return the offline page
return caches.match(cachedFile);
})
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment