Last active
May 16, 2018 20:59
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
}) | |
}) | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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()))