Skip to content

Instantly share code, notes, and snippets.

@osvaldasvalutis
Created October 2, 2017 07:26
Show Gist options
  • Save osvaldasvalutis/cecc4e90f75b0276cf7e1fc69d1fe4f0 to your computer and use it in GitHub Desktop.
Save osvaldasvalutis/cecc4e90f75b0276cf7e1fc69d1fe4f0 to your computer and use it in GitHub Desktop.
self.addEventListener('fetch', event => {
event.respondWith(
// try fetching a resource from the network
fetch(event.request).then(response => {
// cache the resource and serve it
let responseCopy = response.clone();
addToCache(event.request, responseCopy); // this is a custom function, I'll elaborate on it later
return response;
})
.catch(() => {
// the resource could not be fetched from network
// so let's pull it out from cache, otherwise serve the "offline" page
return caches.match(event.request).then(response => response || caches.match('/offline/'));
});
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment