Files
web-camera-category/app/sw.js
T

46 lines
1.3 KiB
JavaScript

// Service Worker — Web Camera Category PWA
// Caches app shell for offline use
const CACHE_NAME = "camcat-v1";
const APP_SHELL = [
"/",
"/index.html",
"/manifest.json",
"/icon-192.png",
"/icon-512.png",
"https://cdn.jsdelivr.net/npm/[email protected]/dist/jszip.min.js",
];
// ── Install: cache app shell ──
self.addEventListener("install", (e) => {
e.waitUntil(
caches.open(CACHE_NAME).then((cache) => cache.addAll(APP_SHELL)).then(() => self.skipWaiting())
);
});
// ── Activate: clean old caches ──
self.addEventListener("activate", (e) => {
e.waitUntil(
caches.keys().then((keys) =>
Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k)))
).then(() => self.clients.claim())
);
});
// ── Fetch: cache-first for app shell, network-first for photos ──
self.addEventListener("fetch", (e) => {
const url = new URL(e.request.url);
// Don't intercept non-GET
if (e.request.method !== "GET") return;
// Cache-first for same-origin
if (url.origin === self.location.origin) {
e.respondWith(
caches.match(e.request).then((cached) => cached || fetch(e.request).then((resp) => {
const clone = resp.clone();
caches.open(CACHE_NAME).then((c) => c.put(e.request, clone));
return resp;
}).catch(() => caches.match("/index.html")))
);
}
});