-
Notifications
You must be signed in to change notification settings - Fork 4
/
service-worker.js
74 lines (69 loc) · 1.58 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
70
71
72
73
74
---
---
const cityNames = [
{%- for city in site.cities -%}
'{{ city.slug }}',
{%- endfor -%}
];
// Add/remove/edit files to cache here
// NOTE: This is really brittle; should be programmatic
const cachedFiles = [
'./',
'index.html',
'main.js',
'service-worker.js',
'not911.webmanifest',
'404.html',
'style.css',
'apple-touch-icon.png',
'icons/dark-theme.svg',
'icons/light-theme.svg',
'icons/phone-dark.svg',
'icons/phone-light.svg',
'favicon.ico',
// include all cities in both their `.html` and non `.html` forms
...cityNames,
...cityNames.map(name => `${name}.html`)
];
const cacheKey = '{{ site.version }}';
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(cacheKey).then((cache) => {
// Cache all the files listed above
return cache.addAll(cachedFiles);
})
);
});
self.addEventListener('activate', event => {
// Delete any cache that isn't the most current
event.waitUntil(
caches.keys().then(keys => Promise.all(
keys.map(key => {
if (key !== cacheKey) {
return caches.delete(key);
}
})
))
);
});
self.addEventListener('fetch', (event) => {
const { request } = event;
if (request.method === 'GET') {
event.respondWith(
fetch(request)
.then(function(response) {
return caches.open(cacheKey).then(function(cache) {
return cache.put(event.request, response.clone()).then(function() {
return response;
})
})
})
.catch((err) => {
console.error(err);
return caches.open(cacheKey).then((cache) => {
return cache.match(request);
});
})
)
}
});