Created
March 11, 2018 20:18
-
-
Save ritikrishu/69c148800490b2b6cfce2dc42955ac57 to your computer and use it in GitHub Desktop.
using cache.put in Service Worker fetch handler
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
/** | |
purpose: | |
for all .png image requests, | |
- look into cache if request-response Pair is already in store | |
- if found, return the object in cache and refresh cache from network | |
- if not found, fetch from network, store in cache and return the response | |
*/ | |
self.addEventListener('fetch', function (event) { | |
const requestUrl = new URL(event.request.url); | |
if(requestUrl.endsWith('.png'){ | |
event.respondWith( | |
caches.open('my-png-image-cache') | |
.then( | |
cache => cache.match(event.request) | |
.then(response => { | |
return response || fetch(event.request).then(function(response) { | |
cache.put(event.request, response.clone()); | |
return response; | |
}); | |
}) | |
) | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment