34 lines
2.1 KiB
JavaScript
34 lines
2.1 KiB
JavaScript
// Offline support: app shell + photos cached on the device. Data changes are queued by the page itself.
|
|
const V = "spike-v1";
|
|
const SHELL = ["/", "manifest.webmanifest", "icon-192.png", "icon-512.png",
|
|
"img/chassis.webp", "img/suspension.webp", "img/wheels.webp", "img/plastics.webp", "img/electrics.webp",
|
|
"img/exhaust-radiator-tank-airfilter.webp", "img/motord.webp"];
|
|
const okToCache = (r) => r && r.ok && !r.redirected && r.type === "basic";
|
|
|
|
self.addEventListener("install", (e) => {
|
|
e.waitUntil(caches.open(V).then((c) => Promise.all(SHELL.map((u) => fetch(u, { credentials: "same-origin" }).then((r) => okToCache(r) && c.put(u, r)).catch(() => {})))).then(() => self.skipWaiting()));
|
|
});
|
|
self.addEventListener("activate", (e) => {
|
|
e.waitUntil(caches.keys().then((ks) => Promise.all(ks.filter((k) => k !== V).map((k) => caches.delete(k)))).then(() => self.clients.claim()));
|
|
});
|
|
self.addEventListener("fetch", (e) => {
|
|
const req = e.request, url = new URL(req.url);
|
|
if (req.method !== "GET" || url.origin !== location.origin) return;
|
|
if (url.pathname.startsWith("/api/") || url.pathname === "/login" || url.pathname === "/logout") return;
|
|
if (url.pathname.startsWith("/uploads/photo-") || url.pathname.startsWith("/img/")) {
|
|
e.respondWith(caches.match(req).then((hit) => hit || fetch(req).then((r) => { if (okToCache(r)) { const c = r.clone(); caches.open(V).then((ch) => ch.put(req, c)); } return r; })));
|
|
return;
|
|
}
|
|
// everything else (page, drawings, manifest): network first, fall back to the saved copy
|
|
e.respondWith(new Promise((resolve) => {
|
|
const key = req.mode === "navigate" ? "/" : req;
|
|
const fallback = () => caches.match(key, { ignoreSearch: url.pathname.startsWith("/uploads/") ? false : true }).then((hit) => resolve(hit || Response.error()));
|
|
const timer = setTimeout(() => caches.match(key, { ignoreSearch: !url.pathname.startsWith("/uploads/") }).then((hit) => hit && resolve(hit)), 4000);
|
|
fetch(req).then((r) => {
|
|
clearTimeout(timer);
|
|
if (okToCache(r)) { const c = r.clone(); caches.open(V).then((ch) => ch.put(key, c)); }
|
|
resolve(r);
|
|
}).catch(() => { clearTimeout(timer); fallback(); });
|
|
}));
|
|
});
|