Everytime I make any change to the index.html
with my Angular project, Service Worker never gets updated and always serves the old cached version on index.html
. How do I fix this (Also, there is no caching at the server end as well as browser)
Here is my ngsw-config
file:
{
"index": "/index.html",
"assetGroups": [{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/manifest.json"
],
"versionedFiles": [
"/*.bundle.css",
"/*.bundle.js",
"/*.chunk.js"
]
}
}, {
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**"
]
}
}]
}
My response headers for the request:
Any idea how to get this fixed?
Thanks
You can force the service worker to delete all previous SW caches (index.html too) with a code like this in the service worker:
const DIRTY_CACHE = 'application-version-number-or-whatever';
self.addEventListener('install', () => {
// Skip over the "waiting" lifecycle state, to ensure that our
// new service worker is activated immediately, even if there's
// another tab open controlled by our older service worker code.
self.skipWaiting();
});
self.addEventListener('activate', event => {
self.registration.unregister();
event.waitUntil(
caches
.keys()
.then(cacheNames =>
cacheNames.filter(cacheName => cacheName.indexOf(DIRTY_CACHE) !== -1),
)
.then(cachesToDelete =>
Promise.all(
cachesToDelete.map(cacheToDelete => caches.delete(cacheToDelete)),
),
)
.then(() => self.clients.claim()),
);
});
A more detailed explanation can be found in this article
Maybe is not the best strategy, but resolves the issue, probably due to a bad expires header.
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