49 lines
1.2 KiB
JavaScript
49 lines
1.2 KiB
JavaScript
const CACHE_NAME = 'stockfill-cache-v1';
|
|
const OFFLINE_URLS = ['/', '/index.html'];
|
|
|
|
self.addEventListener('install', (event) => {
|
|
event.waitUntil(
|
|
caches.open(CACHE_NAME).then((cache) => {
|
|
return cache.addAll(OFFLINE_URLS);
|
|
}),
|
|
);
|
|
});
|
|
|
|
self.addEventListener('activate', (event) => {
|
|
event.waitUntil(
|
|
caches.keys().then((keys) =>
|
|
Promise.all(
|
|
keys.map((key) => {
|
|
if (key !== CACHE_NAME) {
|
|
return caches.delete(key);
|
|
}
|
|
return undefined;
|
|
}),
|
|
),
|
|
),
|
|
);
|
|
});
|
|
|
|
self.addEventListener('fetch', (event) => {
|
|
const { request } = event;
|
|
if (request.method !== 'GET') return;
|
|
|
|
event.respondWith(
|
|
fetch(request)
|
|
.then((response) => {
|
|
const copy = response.clone();
|
|
caches.open(CACHE_NAME).then((cache) => cache.put(request, copy));
|
|
return response;
|
|
})
|
|
.catch(async () => {
|
|
const cached = await caches.match(request);
|
|
if (cached) return cached;
|
|
if (request.mode === 'navigate') {
|
|
const fallback = await caches.match('/index.html');
|
|
if (fallback) return fallback;
|
|
}
|
|
throw new Error('Network error');
|
|
}),
|
|
);
|
|
});
|