Reputation: 1696
I would like to benefits from offline capabilities, so I m making sure to cache on install the page it self and other assets like css and js
self.addEventListener('install', function (event) {
event.waitUntil(caches.open(cacheName).then(cache => cache.addAll([
"/",
self.location.href
])));
self.skipWaiting();
});
as install will be run only once for the worker, how can I make sure that those assets get refreshed on every run or at least from time to time?
Upvotes: 0
Views: 511
Reputation: 2058
You can achieve this also by defining a new cache name each time you deploy a new version of your website:
//change cache name with each deploy
var staticCacheName = 'NewWithEachDeploy';
self.addEventListener('install', function (event) {
event.waitUntil(
caches.open(staticCacheName).then(function (cache) {
return cache.addAll([
'index.html',
'...'
]);
})
);
});
Then on activate you delete all the old caches.
self.addEventListener('activate', function (event) {
event.waitUntil(caches.keys().then(function (keyList) {
return Promise.all(keyList.map(function (cacheKey) {
//delete all caches which do not equal with the current cache name (staticCacheName)
if (cacheKey !== staticCacheName) {
console.log('[ServiceWorker] Removing old cache', cacheKey);
return caches.delete(key);
}
}));
}));
});
This way you make sure all resources are updated at once. Otherwise you can get in trouble. For example your cached html is updated to the newest version but the JS file is still old and this constellation probably does not play well together.
Upvotes: 2
Reputation: 10614
While implementing cache expiration using vanilla JS can be bit challenging, you can try using Workbox by Google. It has this concept of cache expiration
.
A super basic example:
const cacheExpirationPlugin = new workbox.cacheExpiration.CacheExpirationPlugin({
maxEntries: 50,
maxAgeSeconds: 24 * 60 * 60
});
You could read more about it here.
Upvotes: 1