With service workers comes great flexibility and power, but also much responsibility... in terms of keeping the cache under control and not allowing it to grow unnecessarily.
Is there a way to determine the age of a cached item, i.e. the time it has been sitting in the cache, and purge cached items periodically based on age?
I'm thinking here about something along the following lines:
const RUNTIME = 'runtime-cache';
var getAgeOf = function (request) {
return (*time since request was cached*); // <-- but HOW?
};
var purgeRuntimeCache = function (threshold) {
caches.open(RUNTIME).then(function (cache) {
cache.keys().then(function (keys) {
keys.forEach(function (request, index, array) {
cache.match(request).then(function (response) {
if (getAgeOf(request) > threshold) {
console.log('delete old resource from runtime cache: ' + request.url);
cache.delete(request);
}
});
});
});
});
};
The Workbox folks seems to be parsing the 'date' from the response's headers. They also assume the response to be fresh if the date is not available. Check their source for the cacheExpiration plugin over here. I guess one could also save the caching time to IndexedDB or Caches upon fetching the asset from the network for the first time (the asset url as a key for example).
While it's a good exercise to implement something like this by hand and dig into details, my gut says people should generally be better of by using a library to handle the SW. Workbox might be the best option.
Update:
I haven't tried this out myself but I don't see any reason this wouldn't work in practice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With