-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
63 lines (57 loc) · 1.75 KB
/
Copy pathsw.js
File metadata and controls
63 lines (57 loc) · 1.75 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const CACHE = 'asterion-live-v1.1';
const CORE = [
'./',
'./index.html',
'./css/styles.css',
'./js/bootstrap.js',
'./js/app.js',
'./js/versions.js',
'./manifest.webmanifest',
'./assets/asterion-mark.svg',
'./assets/icons/icon-192.png',
'./assets/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((key) => key !== CACHE).map((key) => caches.delete(key))))
.then(() => self.clients.claim())
);
});
async function networkFirst(request) {
const cache = await caches.open(CACHE);
try {
const response = await fetch(request);
if (response.ok) await cache.put(request, response.clone());
return response;
} catch {
return (await cache.match(request)) || (await cache.match('./index.html'));
}
}
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') await cache.put(request, response.clone());
return response;
}
self.addEventListener('fetch', (event) => {
if (event.request.method !== 'GET') return;
const url = new URL(event.request.url);
const sameOrigin = url.origin === self.location.origin;
const approvedCdn = url.hostname === 'cdn.jsdelivr.net';
if (!sameOrigin && !approvedCdn) return;
if (event.request.mode === 'navigate') {
event.respondWith(networkFirst(event.request));
return;
}
event.respondWith(cacheFirst(event.request));
});