69 lines
1.5 KiB
JavaScript
69 lines
1.5 KiB
JavaScript
const CACHE = 'wycz-v1';
|
|
const CORE = [
|
|
'/',
|
|
'/css/style.css',
|
|
'/js/app.js',
|
|
'/manifest.webmanifest',
|
|
'/images/logo.png',
|
|
'/images/icons/icon-96.png',
|
|
'/images/icons/icon-192.png',
|
|
'/images/icons/icon-512.png'
|
|
];
|
|
|
|
self.addEventListener('install', (event) => {
|
|
event.waitUntil(
|
|
caches.open(CACHE)
|
|
.then((cache) => cache.addAll(CORE))
|
|
.then(() => self.skipWaiting())
|
|
);
|
|
});
|
|
|
|
self.addEventListener('activate', (event) => {
|
|
event.waitUntil(
|
|
caches.keys()
|
|
.then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
|
|
.then(() => self.clients.claim())
|
|
);
|
|
});
|
|
|
|
self.addEventListener('fetch', (event) => {
|
|
const req = event.request;
|
|
if (req.method !== 'GET') return;
|
|
|
|
const url = new URL(req.url);
|
|
if (url.origin !== self.location.origin) return;
|
|
|
|
if (url.pathname.startsWith('/api/')) {
|
|
event.respondWith(fetch(req));
|
|
return;
|
|
}
|
|
|
|
if (req.mode === 'navigate') {
|
|
event.respondWith(
|
|
fetch(req)
|
|
.then((res) => {
|
|
const copy = res.clone();
|
|
caches.open(CACHE).then((c) => c.put('/', copy));
|
|
return res;
|
|
})
|
|
.catch(() => caches.match('/'))
|
|
);
|
|
return;
|
|
}
|
|
|
|
event.respondWith(
|
|
caches.match(req).then((cached) => {
|
|
const network = fetch(req)
|
|
.then((res) => {
|
|
if (res.ok) {
|
|
const copy = res.clone();
|
|
caches.open(CACHE).then((c) => c.put(req, copy));
|
|
}
|
|
return res;
|
|
})
|
|
.catch(() => cached);
|
|
return cached || network;
|
|
})
|
|
);
|
|
});
|