58 lines
1.7 KiB
JavaScript
58 lines
1.7 KiB
JavaScript
/* ════════════════════════════════════════════════════
|
|
AMUSEMENT — Service Worker
|
|
Cache-first strategy for offline PWA support
|
|
════════════════════════════════════════════════════ */
|
|
|
|
const CACHE_NAME = 'amusement-v1';
|
|
const ASSETS = [
|
|
'./',
|
|
'./index.html',
|
|
'./style.css',
|
|
'./app.js',
|
|
'./manifest.json',
|
|
];
|
|
|
|
// Install: pre-cache core assets
|
|
self.addEventListener('install', (event) => {
|
|
event.waitUntil(
|
|
caches.open(CACHE_NAME).then((cache) => cache.addAll(ASSETS))
|
|
);
|
|
self.skipWaiting();
|
|
});
|
|
|
|
// Activate: clean old caches
|
|
self.addEventListener('activate', (event) => {
|
|
event.waitUntil(
|
|
caches.keys().then((keys) =>
|
|
Promise.all(
|
|
keys
|
|
.filter((k) => k !== CACHE_NAME)
|
|
.map((k) => caches.delete(k))
|
|
)
|
|
)
|
|
);
|
|
self.clients.claim();
|
|
});
|
|
|
|
// Fetch: cache-first, fallback to network
|
|
self.addEventListener('fetch', (event) => {
|
|
event.respondWith(
|
|
caches.match(event.request).then((cached) => {
|
|
if (cached) return cached;
|
|
return fetch(event.request).then((response) => {
|
|
if (!response || response.status !== 200 || response.type !== 'basic') {
|
|
return response;
|
|
}
|
|
const clone = response.clone();
|
|
caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
|
|
return response;
|
|
});
|
|
}).catch(() => {
|
|
// If both cache and network fail, return offline fallback
|
|
if (event.request.mode === 'navigate') {
|
|
return caches.match('./index.html');
|
|
}
|
|
})
|
|
);
|
|
});
|