Skip to content

Instantly share code, notes, and snippets.

@osvaldasvalutis
Created October 2, 2017 07:27
Show Gist options
  • Save osvaldasvalutis/55cce16632f77be38535c17cd2f3e1ee to your computer and use it in GitHub Desktop.
Save osvaldasvalutis/55cce16632f77be38535c17cd2f3e1ee to your computer and use it in GitHub Desktop.
self.addEventListener('fetch', event => {
event.respondWith(
// check if the resource was cached before
caches.match(event.request).then(response => {
// serve the resource if cached, otherwise fetch it through the network
return response || fetch(event.request).then(response => {
// cache the newly fetched 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(() => {
// serve "offline" page if it couldn't be fetched from network
return caches.match('/offline/');
});
});
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment