-
Notifications
You must be signed in to change notification settings - Fork 2
/
sw.js
51 lines (48 loc) · 1.37 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
const cacheKey = 'GroceryList-v2';
const cacheKeyAllowList = [cacheKey];
const cacheUrls = [
'/index.html',
'/index.css',
'/manifest.json',
'/favicon.ico',
'/grocerylist.js',
'/images/screenshot_wide.png'
];
self.addEventListener('install', (e) => {
e.waitUntil((async () => {
const cache = await caches.open(cacheKey);
await cache.addAll(cacheUrls);
}));
});
self.addEventListener('activate', (e) => {
e.waitUntil((async () => {
const keys = await caches.keys();
return Promise.all(keys.map((key) => {
if (!cacheKeyAllowList.includes(keys)) {
return caches.delete(key);
}
}));
}));
});
self.addEventListener('fetch', (e) => {
const url = e.request.url;
if (e.request.method != 'GET' || url.includes('browser-sync')) {
return;
}
e.respondWith(
(async () => {
try {
const response = await fetch(e.request);
const cache = await caches.open(cacheKey);
cache.put(e.request, response.clone());
return response;
} catch(err) {
const cached_response = await caches.match(e.request);
if (cached_response) {
return cached_response;
}
return err;
}
})(),
);
});