Repository navigation
Expand file tree
/
Copy pathsw.js
More file actions
36 lines (32 loc) · 1.34 KB
/
Copy pathsw.js
File metadata and controls
36 lines (32 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Six Points: the app's own files always come from the network when it is reachable,
// so a new version shows up on the next launch; the last copy is kept for offline use.
// Fonts change rarely, so they are served from the cache once fetched.
const CACHE = 'six-points';
self.addEventListener('install', () => self.skipWaiting());
self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim()));
self.addEventListener('fetch', (event) => {
const { request } = event;
if (request.method !== 'GET') return;
const sameOrigin = new URL(request.url).origin === self.location.origin;
event.respondWith(sameOrigin ? networkFirst(request) : cacheFirst(request));
});
async function networkFirst(request) {
const cache = await caches.open(CACHE);
try {
const response = await fetch(request, { cache: 'no-store' });
if (response.ok) cache.put(request, response.clone());
return response;
} catch (error) {
const cached = await cache.match(request, { ignoreSearch: true });
if (cached) return cached;
throw error;
}
}
async function cacheFirst(request) {
const cache = await caches.open(CACHE);
const cached = await cache.match(request);
if (cached) return cached;
const response = await fetch(request);
if (response.ok || response.type === 'opaque') cache.put(request, response.clone());
return response;
}