54 lines
1.6 KiB
JavaScript
54 lines
1.6 KiB
JavaScript
const CACHE_NAME = 'radiocast-core-v2';
|
|
const CORE_ASSETS = [
|
|
'.',
|
|
'index.html',
|
|
'main.js',
|
|
'styles.css',
|
|
'stations.json',
|
|
'assets/favicon_io/android-chrome-192x192.png',
|
|
'assets/favicon_io/android-chrome-512x512.png',
|
|
'assets/favicon_io/apple-touch-icon.png'
|
|
];
|
|
|
|
self.addEventListener('install', (event) => {
|
|
// Activate updated SW as soon as it's installed.
|
|
self.skipWaiting();
|
|
event.waitUntil(
|
|
caches.open(CACHE_NAME).then((cache) => cache.addAll(CORE_ASSETS))
|
|
);
|
|
});
|
|
|
|
self.addEventListener('activate', (event) => {
|
|
event.waitUntil(
|
|
Promise.all([
|
|
self.clients.claim(),
|
|
caches.keys().then((keys) => Promise.all(
|
|
keys.map((k) => { if (k !== CACHE_NAME) return caches.delete(k); return null; })
|
|
)),
|
|
])
|
|
);
|
|
});
|
|
|
|
self.addEventListener('fetch', (event) => {
|
|
// Only handle GET requests
|
|
if (event.request.method !== 'GET') return;
|
|
|
|
event.respondWith(
|
|
caches.match(event.request).then((cached) => {
|
|
if (cached) return cached;
|
|
return fetch(event.request).then((networkResp) => {
|
|
// Optionally cache new resources (best-effort)
|
|
try {
|
|
const respClone = networkResp.clone();
|
|
caches.open(CACHE_NAME).then((cache) => cache.put(event.request, respClone)).catch(()=>{});
|
|
} catch (e) {}
|
|
return networkResp;
|
|
}).catch(() => {
|
|
// If offline and HTML navigation, return cached index.html
|
|
if (event.request.mode === 'navigate') return caches.match('index.html');
|
|
return new Response('', { status: 503, statusText: 'Service Unavailable' });
|
|
});
|
|
})
|
|
);
|
|
});
|