77 lines
2.1 KiB
JavaScript
77 lines
2.1 KiB
JavaScript
const CACHE_VERSION = 'v1';
|
|
const CACHE_NAME = `fermdez-games-${CACHE_VERSION}`;
|
|
const CORE_ASSETS = [
|
|
'/',
|
|
'/index.html',
|
|
'/media/favicon.ico',
|
|
'/manifest.webmanifest'
|
|
];
|
|
|
|
self.addEventListener('install', event => {
|
|
event.waitUntil(
|
|
caches.open(CACHE_NAME)
|
|
.then(cache => cache.addAll(CORE_ASSETS))
|
|
.then(() => self.skipWaiting())
|
|
);
|
|
});
|
|
|
|
self.addEventListener('activate', event => {
|
|
event.waitUntil(
|
|
(async () => {
|
|
const keys = await caches.keys();
|
|
await Promise.all(keys.map(k => k !== CACHE_NAME && caches.delete(k)));
|
|
await self.clients.claim();
|
|
})()
|
|
);
|
|
});
|
|
|
|
const cacheFirst = async (req) => {
|
|
const cache = await caches.open(CACHE_NAME);
|
|
const cached = await cache.match(req);
|
|
if (cached) return cached;
|
|
const resp = await fetch(req);
|
|
if (resp && resp.status === 200 && req.method === 'GET') {
|
|
cache.put(req, resp.clone());
|
|
}
|
|
return resp;
|
|
};
|
|
|
|
const networkFirst = async (req) => {
|
|
const cache = await caches.open(CACHE_NAME);
|
|
try {
|
|
const resp = await fetch(req);
|
|
if (resp && resp.status === 200) {
|
|
cache.put(req, resp.clone());
|
|
}
|
|
return resp;
|
|
} catch (err) {
|
|
const cached = await cache.match(req);
|
|
if (cached) return cached;
|
|
if (req.mode === 'navigate') {
|
|
return cache.match('/index.html');
|
|
}
|
|
throw err;
|
|
}
|
|
};
|
|
|
|
self.addEventListener('fetch', event => {
|
|
const { request } = event;
|
|
if (request.method !== 'GET') return;
|
|
const accept = request.headers.get('accept') || '';
|
|
const url = new URL(request.url);
|
|
const isSameOrigin = url.origin === self.location.origin;
|
|
const isHTML = accept.includes('text/html');
|
|
const isStaticAsset = /\.(?:css|js|png|jpg|jpeg|svg|ico|webmanifest|mp3|wav)$/.test(url.pathname);
|
|
if (isHTML) {
|
|
event.respondWith(networkFirst(request));
|
|
} else if (isSameOrigin && isStaticAsset) {
|
|
event.respondWith(cacheFirst(request));
|
|
}
|
|
});
|
|
|
|
// Optional: handle message to trigger skipWaiting from client
|
|
self.addEventListener('message', event => {
|
|
if (event.data && event.data.type === 'SKIP_WAITING') {
|
|
self.skipWaiting();
|
|
}
|
|
}); |