I'm using the following logic in my service worker (in my own words):
If cache exists, use it, but also update cache from the network for later
event.respondWith( // on `fetch`
caches.open(CACHE)
.then(function(cache) {
return cache.match(request);
})
.then(function(matching) {
if (matching) {
requestAndUpdateCache(event);
return matching;
}
...
In addition to responding with the cached response, I also run this function called requestAndUpdateCache.
function requestAndUpdateCache(event){
var url = event.request.url + '?t=' + new Date().getTime();
fetch(url)
.then(function(response){
if (response && response.status === 200){
caches.open(CACHE)
.then(function(cache){
cache.put(event.request, response.clone());
});
}
}, function(error){
console.log(error);
});
}
Questions: Does this function and its placement make sense to accomplish the logic outlined above?