When I update the service worker, I close and reopen the page and I get the console log that the new service worker has been installed and activated, and the old cache has been deleted. However, the files listed to be added to the cache are not fetched from the server again, they are stale versions from hours ago. There's no way to make it update the files short of clearing storage in the Chrome dev tools.
How can I make my service worker populate it's cache with fresh files when a new version is installed?
For example, "stylesheet.css" is still an old version when the service worker updates:
let cacheName = "abc_web_v1_15";
self.addEventListener('install', (event) => {
console.log('[Service Worker] Install');
event.waitUntil(
caches.open(cacheName).then(function (cache) {
return cache.addAll([
"/".
"/stylesheet.css",
...
]);
})
);
});
self.addEventListener('fetch', (e) => {
e.respondWith(
caches.match(e.request).then(function (r) {
console.log('[Service Worker] Fetching resource: ' + cacheName + ' ' + e.request.url);
if (r) {
console.log(cacheName + ' returning cached ' + e.request);
return r;
} else {
console.log(cacheName + ' returning fetched ' + e.request);
return fetch(e.request);
}
})
)
});
self.addEventListener('activate', (e) => {
console.log('[Service Worker] Activate');
e.waitUntil(
caches.keys().then((keyList) => {
return Promise.all(keyList.map((key) => {
if (cacheName.indexOf(key) === -1) {
console.log(`[Service Worker] Removing Cached Files from Cach-${key}`);
return caches.delete(key);
}
}));
})
);
});