Last active
May 5, 2020 21:25
-
-
Save adrianholovaty/e3f8f4b522430dabcf21 to your computer and use it in GitHub Desktop.
Better example of custom service worker cache keys
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
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