Files
web-camera-category/app/sw.js
T
2026-10-24 17:32:25 +07:00

78 lines
2.2 KiB
JavaScript

// Service Worker — CamCat 2.0
// กลยุทธ์: navigation = network-first (ได้เวอร์ชันใหม่ก่อน) · asset = stale-while-revalidate
const CACHE = "camcat-v2.1.1";
const ASSETS = [
"./",
"./index.html",
"./manifest.json",
"./css/app.css",
"./js/config.js",
"./js/naming.js",
"./js/db.js",
"./js/exif.js",
"./js/device.js",
"./js/camera.js",
"./js/archive.js",
"./js/ui.js",
"./js/main.js",
"./vendor/jszip.min.js",
"./vendor/piexif.js",
"./vendor/qrcode.min.js",
"./icon-192.png",
"./icon-512.png",
];
self.addEventListener("install", (e) => {
e.waitUntil(
caches.open(CACHE)
.then((c) => Promise.allSettled(ASSETS.map((u) => c.add(new Request(u, { cache: "reload" })))))
.then(() => self.skipWaiting())
);
});
self.addEventListener("activate", (e) => {
e.waitUntil(
caches.keys()
.then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
.then(() => self.clients.claim())
);
});
self.addEventListener("fetch", (e) => {
const req = e.request;
if (req.method !== "GET") return;
const url = new URL(req.url);
if (url.origin !== self.location.origin) return;
// หน้าเว็บ: เอาจากเครือข่ายก่อน ถ้าออฟไลน์ค่อยใช้แคช
if (req.mode === "navigate") {
e.respondWith(
fetch(req)
.then((resp) => {
const clone = resp.clone();
caches.open(CACHE).then((c) => c.put(req, clone));
return resp;
})
.catch(() => caches.match(req).then((r) => r || caches.match("./index.html")))
);
return;
}
// ไฟล์อื่น: คืนแคชทันที + อัปเดตเบื้องหลัง
e.respondWith(
caches.match(req).then((cached) => {
const network = fetch(req)
.then((resp) => {
if (resp && resp.ok) {
const clone = resp.clone();
caches.open(CACHE).then((c) => c.put(req, clone));
}
return resp;
})
.catch(() => cached);
return cached || network;
})
);
});