Skip to content

Instantly share code, notes, and snippets.

@ritikrishu
Last active May 16, 2018 20:59
Show Gist options
  • Save ritikrishu/5bcb5de4733813afeee98f9148136d05 to your computer and use it in GitHub Desktop.
Save ritikrishu/5bcb5de4733813afeee98f9148136d05 to your computer and use it in GitHub Desktop.
serve content from cache if available. otherwise serve from network but store for future usage
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.catch(_ => {
//data not found in cache, goto network
fetch(event.request)
.then(res => {
if(res){
caches.open('cache first category data', cache => cache.put(event.request, res))
return res
}
})
})
);
});
@adactio
Copy link

adactio commented May 16, 2018

I don't think this will work.

On line 4, the catch will never fire, even if the resource can't be found in the cache (I know, it's very unexpected behaviour).

On line 9, you need to clone the response to put it in the cache (because the response is a stream, it can only be used once):

caches.open('cache first category data', cache => cache.put(event.request, res.clone()))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment