sw-tips
sw-tips copied to clipboard
The function cacheVersioned() doesn't update to newer assets
in the section cache smarter, the function cacheVersioned()
is intended to cache assets that may change over time.
async function cacheVersioned(version, assets) {
const exists = await caches.has(`version-${version}`);
if (!exists) {
const requests = assets.map(asset => new Request(asset));
const preCachedResponses =
await Promise.all(requests.map(req => caches.match(req)));
const cache = await caches.open(`version-${version}`);
return Promise.all(requests.map((request, idx) => {
return preCachedResponses[idx]
? cache.put(request, preCachedResponses[idx].clone())
: cache.add(request);
}));
}
}
But, AFAIK, the code will fail to do so. The function only checks if a Response
already exists, not the content of the response (since that is impossible).
The technique will only work if the URL itself changes (hashes?).
Good point! Should check if the response is stale (via cache-control
header) before copying.
i figured another way out - cache busted URLs. :sweat_smile:
i am using this caching logic in my project and it works just fine.