1
0
Fork 0
fahrPool/web/public/sw.js

55 lines
1.6 KiB
JavaScript

// VERSION erhoehen, wenn sich offline.html aendert (wird nur beim Install gecacht).
const VERSION = "v1";
const CACHE = `pwa-${VERSION}`;
const PRECACHE = ["/offline.html"];
function istCachebar(pathname) {
return (
pathname.startsWith("/_next/static/") ||
pathname.startsWith("/app-icon/") ||
pathname.endsWith(".woff2")
);
}
self.addEventListener("install", (event) => {
event.waitUntil(caches.open(CACHE).then((c) => c.addAll(PRECACHE)).then(() => self.skipWaiting()));
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches
.keys()
.then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
.then(() => self.clients.claim())
);
});
self.addEventListener("fetch", (event) => {
const request = event.request;
if (request.method !== "GET") return;
const url = new URL(request.url);
if (url.origin !== self.location.origin) return;
if (request.mode === "navigate") {
event.respondWith(fetch(request).catch(() => caches.match("/offline.html")));
return;
}
if (!istCachebar(url.pathname)) return;
event.respondWith(
caches.open(CACHE).then(async (cache) => {
const treffer = await cache.match(request);
if (treffer) return treffer;
const antwort = await fetch(request);
const cc = antwort.headers.get("Cache-Control") || "";
if (antwort.status === 200 && !cc.includes("no-store")) {
event.waitUntil(cache.put(request, antwort.clone()).catch(() => {}));
}
return antwort;
})
);
});
if (typeof module !== "undefined") module.exports = { istCachebar };