Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Better example of custom service worker cache keys
var jsonDataRe = /example\.com\/(.*\.json)/;
self.addEventListener('fetch', function(event) {
var request = event.request,
match = jsonDataRe.exec(request.url);
if (match) {
// Use regex capturing to grab only the bit of the URL
// that we care about, ignoring query string, etc.
var cacheRequest = new Request(match[1]);
event.respondWith(
caches.match(cacheRequest).then(function(response) {
return response || fetch(request).then(function(response) {
caches.open('mycache').then(function(cache) {
cache.put(cacheRequest, response);
})
return response;
});
})
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment