Skip to content

Instantly share code, notes, and snippets.

@ritikrishu
Created March 11, 2018 20:18
Show Gist options
  • Save ritikrishu/69c148800490b2b6cfce2dc42955ac57 to your computer and use it in GitHub Desktop.
Save ritikrishu/69c148800490b2b6cfce2dc42955ac57 to your computer and use it in GitHub Desktop.
using cache.put in Service Worker fetch handler
/**
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