Skip to content

Instantly share code, notes, and snippets.

@adrianholovaty
Last active May 5, 2020 21:25
Show Gist options
  • Save adrianholovaty/e3f8f4b522430dabcf21 to your computer and use it in GitHub Desktop.
Save adrianholovaty/e3f8f4b522430dabcf21 to your computer and use it in GitHub Desktop.
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