// service-worker.js const CACHE_NAME = "site-static-v1"; const assetsToCache = ["/", "/index.html", "/css/style.css", "/js/script.js"]; // Install event self.addEventListener("install", (event) => { event.waitUntil( caches.open(CACHE_NAME).then((cache) => { cache.addAll(assetsToCache); }) ); }); // Fetch event self.addEventListener("fetch", (event) => { event.respondWith( caches.match(event.request).then((cacheResponse) => { return cacheResponse || fetch(event.request); }) ); });
In the original code, the service worker caches the assets on install, but it doesn’t update the cache when the assets change. This means that if you update your CSS or JS, the service worker will still serve the old version.
To fix this we can use the cache.put() method to update the cache when the assets change.
// service-worker.js const CACHE_NAME = "site-static-v1"; const assetsToCache = ["/", "/index.html", "/css/style.css", "/js/script.js"]; // Install event self.addEventListener("install", (event) => { event.waitUntil( caches.open(CACHE_NAME).then((cache) => { cache.addAll(assetsToCache); }) ); }); // Fetch event self.addEventListener("fetch", (event) => { event.respondWith( caches.match(event.request).then((cacheResponse) => { return ( cacheResponse || fetch(event.request).then((fetchResponse) => { return caches.open(CACHE_NAME).then((cache) => { cache.put(event.request.url, fetchResponse.clone()); return fetchResponse; }); }) ); }) ); });
Before you get too confident, just remember, service workers were created to keep you humble (allegedly).