58 lines
1.5 KiB
JavaScript
58 lines
1.5 KiB
JavaScript
const CACHE_NAME = 'shangma-pwa-v1';
|
|
const APP_SHELL = [
|
|
'/offline.html',
|
|
'/manifest.webmanifest',
|
|
'/pwa/app-icon.svg',
|
|
'/pwa/register.js'
|
|
];
|
|
|
|
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.startsWith('shangma-pwa-') && key !== CACHE_NAME)
|
|
.map((key) => caches.delete(key))
|
|
))
|
|
);
|
|
self.clients.claim();
|
|
});
|
|
|
|
self.addEventListener('fetch', (event) => {
|
|
const request = event.request;
|
|
const url = new URL(request.url);
|
|
|
|
if (request.method !== 'GET' || url.origin !== self.location.origin) {
|
|
return;
|
|
}
|
|
|
|
if (request.mode === 'navigate') {
|
|
event.respondWith(
|
|
fetch(request).catch(() => caches.match('/offline.html'))
|
|
);
|
|
return;
|
|
}
|
|
|
|
// Only public versioned/static UI assets are cached. HTML, APIs, downloads,
|
|
// uploads, scores and all authenticated data remain network-only.
|
|
if (!url.pathname.startsWith('/static/') && !url.pathname.startsWith('/pwa/')) {
|
|
return;
|
|
}
|
|
|
|
event.respondWith(
|
|
caches.match(request).then((cached) => {
|
|
if (cached) return cached;
|
|
|
|
return fetch(request).then((response) => {
|
|
if (!response.ok || response.type !== 'basic') return response;
|
|
const copy = response.clone();
|
|
caches.open(CACHE_NAME).then((cache) => cache.put(request, copy));
|
|
return response;
|
|
});
|
|
})
|
|
);
|
|
});
|