52 lines
1.4 KiB
JavaScript
52 lines
1.4 KiB
JavaScript
// AboveTheMark Service Worker for Offline Support
|
|
const CACHE_NAME = 'abovethemark-v1';
|
|
const APP_SHELL = ['./', './index.html', './manifest.json', './favicon.svg'];
|
|
|
|
self.addEventListener('install', (event) => {
|
|
self.skipWaiting();
|
|
event.waitUntil(
|
|
caches.open(CACHE_NAME).then((cache) => cache.addAll(APP_SHELL))
|
|
);
|
|
});
|
|
|
|
self.addEventListener('activate', (event) => {
|
|
event.waitUntil(
|
|
caches.keys().then((keys) =>
|
|
Promise.all(
|
|
keys.filter((key) => key !== CACHE_NAME).map((key) => caches.delete(key))
|
|
)
|
|
).then(() => self.clients.claim())
|
|
);
|
|
});
|
|
|
|
self.addEventListener('fetch', (event) => {
|
|
const { request } = event;
|
|
|
|
// Only handle same-origin GET requests
|
|
if (request.method !== 'GET' || new URL(request.url).origin !== self.location.origin) {
|
|
return;
|
|
}
|
|
|
|
// Navigation requests: network-first, fall back to cached app shell offline
|
|
if (request.mode === 'navigate') {
|
|
event.respondWith(
|
|
fetch(request).catch(() => caches.match('./index.html'))
|
|
);
|
|
return;
|
|
}
|
|
|
|
// Static assets: cache-first, then populate the cache
|
|
event.respondWith(
|
|
caches.match(request).then((cached) => {
|
|
if (cached) return cached;
|
|
return fetch(request).then((response) => {
|
|
if (response.ok) {
|
|
const copy = response.clone();
|
|
caches.open(CACHE_NAME).then((cache) => cache.put(request, copy));
|
|
}
|
|
return response;
|
|
});
|
|
})
|
|
);
|
|
});
|