-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
75 lines (70 loc) · 2.24 KB
/
sw.js
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
64
65
66
67
68
69
70
71
72
73
74
75
const fontsCacheVersion = 'v2';
const fontCacheName = '-font-cache';
let allClients = [];
self.addEventListener('install', (installEvent) => {
installEvent.waitUntil(
(async () => {
const cacheNames = await caches.keys();
cacheNames.forEach((cacheName) => {
if (
cacheName.endsWith(fontCacheName) &&
cacheName !== fontsCacheVersion + fontCacheName
) {
caches.delete(cacheName);
}
});
})()
);
self.skipWaiting();
});
self.addEventListener('activate', async (activateEvent) => {
activateEvent.waitUntil(
(async () => {
self.clients.claim().then(() => {
self.clients.matchAll().then((res) => (allClients = res));
});
})()
);
});
self.addEventListener('fetch', (fetchEvent) => {
const request = fetchEvent.request;
const requestURL = new URL(request.url);
const clientURL = allClients[0] ? new URL(allClients[0].url) : 'notthehost';
if (requestURL.host === clientURL.host) {
// temporary fix
if (requestURL.pathname.includes('/fonts/')) {
fetchEvent.respondWith(
(async () => {
const responseFromCache = await caches.match(request);
if (responseFromCache) return responseFromCache;
const responseFromNetwork = await fetch(request);
const responseFromNetworkClone = responseFromNetwork.clone();
if (responseFromNetwork.ok) {
const fontCache = await caches.open(
fontsCacheVersion + fontCacheName
);
fontCache.put(request, responseFromNetworkClone);
}
return responseFromNetwork;
})()
);
} else {
const cached = caches.match(request);
const fetched = fetch(request);
const fetchedCopy = fetched.then((res) => res.clone());
fetchEvent.respondWith(
Promise.race([fetched.catch((_) => cached), cached])
.then((res) => res || fetched)
.catch((_) => new Response(null, { status: 404 }))
);
fetchEvent.waitUntil(
Promise.all([
fetchedCopy,
caches.open(clientURL.pathname.match('.*/(.*)/')[1]),
])
.then(([response, cache]) => cache.put(request, response))
.catch((_) => {})
);
}
}
});