-
Notifications
You must be signed in to change notification settings - Fork 3
/
service-worker.js
51 lines (41 loc) · 1.19 KB
/
service-worker.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
const putInCache = async(request, response) => {
// Try excluding this file from cache
if (request.url.endsWith('service-worker.js')) {
console.log('not caching service-worker.js file');
return;
}
const cache = await caches.open('v1.12'); // update on deploy. Will that be enough, or is this script itself cached?
await cache.put(request, response);
};
// Retrieve from cache if available
const cacheFirst = async({ request, fallbackUrl }) => {
const fromCache = await caches.match(request);
if (fromCache) {
return fromCache;
}
try {
const fromNetwork = await fetch(request);
// Clone, because a response can only be consumed once
putInCache(request, fromNetwork.clone());
return fromNetwork;
} catch (error) {
const fallback = await caches.match(fallbackUrl);
return (fallback)
? fallback
: new Response('Network error', {
status: 408,
headers: { 'Content-Type': 'text/plain' },
});
}
};
self.addEventListener('fetch', (event) => {
if (!event.request.url.startsWith('http')) {
return;
}
event.respondWith(
cacheFirst({
request: event.request,
fallbackUrl: '/offline.html',
})
);
});