Repository navigation
Expand file tree
/
Copy pathworker.js
More file actions
71 lines (64 loc) · 2.04 KB
/
Copy pathworker.js
File metadata and controls
71 lines (64 loc) · 2.04 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
64
65
66
67
68
69
70
71
/*
Service Workers are a required component of PWAs. Without a worker that can cache files, control outgoing commands and optionally receive push notifications, PWAs are not able to be installed and used by a user.
*/
const version = '0.9'
const addResourcesToCache = async (resources) => {
const cache = await caches.open(version);
await cache.addAll(resources);
};
const putInCache = async (request, response) => {
console.log(`putting in cache ${request.url}`)
const cache = await caches.open(version);
await cache.put(request, response);
};
const cacheFirst = async ({ request }) => {
// First try to get the resource from the cache
const responseFromCache = await caches.match(request);
if (responseFromCache) {
return responseFromCache;
}
// Next try to get the resource from the network
try {
const responseFromNetwork = await fetch(request.clone());
// response may be used only once
// we need to save clone to put one copy in cache
// and serve second one
putInCache(request, responseFromNetwork.clone());
return responseFromNetwork;
} catch (error) {
const fallbackResponse = await caches.match(fallbackUrl);
if (fallbackResponse) {
return fallbackResponse;
}
// when even the fallback response is not available,
// there is nothing we can do, but we must always
// return a Response object
return new Response('Network error happened', {
status: 408,
headers: { 'Content-Type': 'text/plain' },
})
}
}
self.addEventListener('activate', (event) => {
});
self.addEventListener('install', (event) => {
event.waitUntil(
/* add any other offline resources here */
addResourcesToCache([
'/',
'/index.html',
'/index.css',
'/index.js',
'/trystero-ipfs.min.js'
])
)
})
self.addEventListener('fetch', (event) => {
event.respondWith(
cacheFirst(
{
request: event.request
}
)
)
})