with regards to this api https://developer.mozilla.org/en-US/docs/Web/API/Cache, I'd like to also set the cache lifetime
.
let's say, cache this request for no longer than 10 minutes
with regards to this api https://developer.mozilla.org/en-US/docs/Web/API/Cache, I'd like to also set the cache lifetime
.
let's say, cache this request for no longer than 10 minutes
That is, unfortunately, not possible.
The doc you linked specifically states that items in the cache objects provided by the Cache API don't automatically get updated nor deleted. You have to implement that sort of logic on your own.
You should note that libraries eg. Workbox already does that for you. You could take advantage of that if other functionality suits your usecase.
This is how I implemented this without Workbox. (If you can switch to Workbox, please do, if not – keep reading)
x-sw-cache-timestamp
.x-sw-cache-timestamp
with currentTime and if exceeded the 10 min window, fetch from network.function onFetchComplete(response) {
var timestampHeader = {}
timestampHeader['x-sw-cache-timestamp'] = Date.now()
return serviceWorker
.cloneResponse(response, timestampHeader)
.then(function (responseCopy) {
cache.add(request, responseCopy.clone())
return responseCopy
})
}
serviceWorker.cloneResponse = function (response, extraHeaders) {
if (!response) {
return serviceWorker.Promise.resolve()
}
var init = {
status: response.status,
statusText: response.statusText,
headers: extraHeaders || {},
}
response.headers.forEach(function (val, key) {
init.headers[key] = val
})
return response.blob().then(function (blob) {
return new serviceWorker.Response(blob, init)
})
}
Hope this helps!
You can dynamically create cache names that encode their creation time and max age, something simple like: ${dateStr}_${maxAgeMs}
. Then when intercepting a fetch in your service worker you can look through the existing caches using caches.keys
and find one that isn't expired using just its name and match against that, or create a new one if they're all expired and populate it with the incoming fetches. This also gives you an opportunity to delete the expired caches.
I needed to do this as well and took a look at the mentioned workbox project, seems like they're doing a similar thing with IndexedDB storage but that seems overkill for the ask.