let CACHE_STATIC_NAME = "static-v2"; let CACHE_DYNAMIC_NAME = "dynamic-v3"; self.addEventListener("install", function (event) { console.log("[SW install]", event); self.skipWaiting(); event.waitUntil( caches.open(CACHE_STATIC_NAME).then((cache) => { console.log("[SW precache]"); return cache.addAll(["/", "/index.html", "/offline.html", "/help/index.html", "/js/app.js"]); }), ); }); self.addEventListener("activate", function (event) { console.log("[SW activate]", event); event.waitUntil( caches.keys().then((keys) => { console.log("removing the old cache"); return Promise.all( keys.map((key) => { if (key !== CACHE_STATIC_NAME) { return caches.delete(key); } }), ); }), ); return self.clients.claim(); }); self.addEventListener("fetch", function (event) { event.respondWith( caches.match(event.request).then((res) => { console.log("res", res); if (res) { return res; } else { return fetch(event.request.url) .then((res) => { return caches.open(CACHE_DYNAMIC_NAME).then((cache) => { cache.put(event.request.url, res.clone()); return res; }); }) .catch(() => { return caches.open(CACHE_STATIC_NAME).then((cache) => { return cache.match("/offline.html"); }); }); } }), ); });