77 lines
2.4 KiB
Plaintext
77 lines
2.4 KiB
Plaintext
/* Offline app shell for the Interval Timer PWA. */
|
|
|
|
const CACHE = 'interval-timer-v1';
|
|
|
|
const ASSETS = [
|
|
'./',
|
|
'./index.html',
|
|
'./styles.css',
|
|
'./app.js',
|
|
'./manifest.webmanifest',
|
|
'./icons/icon-192.png',
|
|
'./icons/icon-512.png',
|
|
'./icons/icon-maskable-512.png',
|
|
];
|
|
|
|
self.addEventListener('install', (event) => {
|
|
event.waitUntil(
|
|
caches.open(CACHE)
|
|
.then((cache) => cache.addAll(ASSETS))
|
|
.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 { request } = event;
|
|
if (request.method !== 'GET' || new URL(request.url).origin !== self.location.origin) return;
|
|
|
|
// Navigations: try the network, fall back to the cached shell when offline.
|
|
if (request.mode === 'navigate') {
|
|
event.respondWith(
|
|
fetch(request)
|
|
.then((response) => {
|
|
const copy = response.clone();
|
|
caches.open(CACHE).then((cache) => cache.put('./index.html', copy));
|
|
return response;
|
|
})
|
|
.catch(() => caches.match('./index.html'))
|
|
);
|
|
return;
|
|
}
|
|
|
|
// Everything else: cache first, refresh in the background.
|
|
event.respondWith(
|
|
caches.match(request).then((cached) => {
|
|
const network = fetch(request)
|
|
.then((response) => {
|
|
if (response && response.status === 200 && response.type === 'basic') {
|
|
const copy = response.clone();
|
|
caches.open(CACHE).then((cache) => cache.put(request, copy));
|
|
}
|
|
return response;
|
|
})
|
|
.catch(() => cached);
|
|
return cached || network;
|
|
})
|
|
);
|
|
});
|
|
q¼Â¤}È |