-
Notifications
You must be signed in to change notification settings - Fork 2
/
service-worker.js
69 lines (62 loc) · 1.73 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const CACHE_NAME = 'todo-app';
/* Add relative URL of all the static content you want to store in
* cache storage (this will help us use our app offline)*/
let resourcesToCache = [
'index.html',
'manifest.json',
'favicon.ico',
'static/192.png',
'static/512.png',
'js/App.mjs',
'js/Footer/index.mjs',
'js/Header/index.mjs',
'js/render.mjs',
'js/ToDo/Filters.mjs',
'js/ToDo/Footer.mjs',
'js/ToDo/index.mjs',
'js/ToDo/Item.mjs',
'js/ToDo/List.mjs',
'js/ToDo/store.mjs',
'js/ToDo/Todos.mjs',
'js/ToDo/useFilter.mjs',
'js/ToDo/useTodos.mjs',
'js/util/groupBy.mjs',
];
self.addEventListener('install', (e) => {
e.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll(resourcesToCache);
})
);
});
// Cache and return requests
self.addEventListener('fetch', (e) => {
e.respondWith(
caches.match(e.request).then(async (response) => {
if (response) return response;
const networkResponse = await fetch(e.request);
const clonedResponse = networkResponse.clone();
// save response to runtime cache for later use
// https://www.harrytheo.com/blog/2021/03/cache-handling-with-service-workers-and-the-cache-api/#runtime-caching--vanilla
const runtimeCache = await caches.open('runtime-cache');
runtimeCache.put(e.request, networkResponse);
// respond with the cloned network response
return Promise.resolve(clonedResponse);
})
);
});
// Update a service worker
const cacheWhitelist = ['todo-app'];
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});