81 lines
2.5 KiB
JavaScript
81 lines
2.5 KiB
JavaScript
const CACHE_NAME = 'rhetorikmaster-v5';
|
|
const STATIC_ASSETS = [
|
|
'/',
|
|
'/index.html',
|
|
'/rhetorik_trainer_quiz.html',
|
|
'/favicon.svg',
|
|
'/manifest.json',
|
|
'/icon-192.png',
|
|
'/icon-512.png',
|
|
'https://cdn.tailwindcss.com',
|
|
'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css',
|
|
'https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap'
|
|
];
|
|
|
|
self.addEventListener('install', (event) => {
|
|
event.waitUntil(
|
|
caches.open(CACHE_NAME).then((cache) => {
|
|
return cache.addAll(STATIC_ASSETS).catch((err) => {
|
|
console.warn('Precache partial failure:', err);
|
|
});
|
|
})
|
|
);
|
|
self.skipWaiting();
|
|
});
|
|
|
|
self.addEventListener('activate', (event) => {
|
|
event.waitUntil(
|
|
caches.keys().then((cacheNames) => {
|
|
return Promise.all(
|
|
cacheNames.map((name) => {
|
|
if (name !== CACHE_NAME) {
|
|
console.log('Cleaning old cache:', name);
|
|
return caches.delete(name);
|
|
}
|
|
})
|
|
);
|
|
}).then(() => self.clients.claim())
|
|
);
|
|
});
|
|
|
|
self.addEventListener('fetch', (event) => {
|
|
const request = event.request;
|
|
const isHtmlNavigation = request.mode === 'navigate' ||
|
|
(request.method === 'GET' && request.headers.get('accept') && request.headers.get('accept').includes('text/html'));
|
|
|
|
if (isHtmlNavigation) {
|
|
// Network-First for HTML/Navigation: Always fetch fresh HTML from server, fallback to cache if offline
|
|
event.respondWith(
|
|
fetch(request)
|
|
.then((networkResponse) => {
|
|
if (networkResponse && networkResponse.status === 200) {
|
|
const copy = networkResponse.clone();
|
|
caches.open(CACHE_NAME).then((cache) => cache.put(request, copy));
|
|
}
|
|
return networkResponse;
|
|
})
|
|
.catch(() => {
|
|
return caches.match(request).then((cached) => cached || caches.match('/rhetorik_trainer_quiz.html') || caches.match('/'));
|
|
})
|
|
);
|
|
return;
|
|
}
|
|
|
|
// Stale-While-Revalidate for other static assets (CSS, fonts, images)
|
|
event.respondWith(
|
|
caches.match(request).then((cachedResponse) => {
|
|
const fetchPromise = fetch(request).then((networkResponse) => {
|
|
if (networkResponse && networkResponse.status === 200) {
|
|
const responseToCache = networkResponse.clone();
|
|
caches.open(CACHE_NAME).then((cache) => {
|
|
cache.put(request, responseToCache);
|
|
});
|
|
}
|
|
return networkResponse;
|
|
}).catch(() => cachedResponse);
|
|
|
|
return cachedResponse || fetchPromise;
|
|
})
|
|
);
|
|
});
|