kaikai_test/public/mobile-sw.js
2026-05-14 18:53:53 +08:00

53 lines
1.3 KiB
JavaScript

const CACHE_NAME = "video-hotness-mobile-offline-v1";
const APP_SHELL = [
"/mobile.html",
"/mobile.css",
"/mobile.js",
"/manifest.webmanifest",
];
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => cache.addAll(APP_SHELL)),
);
self.skipWaiting();
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys().then((keys) => Promise.all(
keys.filter((key) => key !== CACHE_NAME).map((key) => caches.delete(key)),
)),
);
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 (url.pathname === "/" || APP_SHELL.includes(url.pathname)) {
event.respondWith(cacheFirst(request));
return;
}
if (url.pathname.startsWith("/api/")) {
event.respondWith(fetch(request));
}
});
async function cacheFirst(request) {
const cached = await caches.match(request);
if (cached) return cached;
try {
const response = await fetch(request);
const cache = await caches.open(CACHE_NAME);
cache.put(request, response.clone());
return response;
} catch {
return caches.match("/mobile.html");
}
}