-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice-worker.html
61 lines (56 loc) · 1.81 KB
/
service-worker.html
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
---js
{
permalink: "service-worker.js",
built: function () {
let s = (new Date).toLocaleString('en-US', { hour12: false })
s = s.slice(0, -3) // remove seconds
s = s.replace(',', '').replace(':', '')
s = s.replace(/(\d+)\/(\d+)\/(\d+) /, "$3$1$2-")
return s
}
}
---
'use strict';
const CACHE_NAME = "{{built}}";
const FILES = [
{{> files }}
];
// NOTE: This is "install" of the service worker, not the app
self.addEventListener('install', (evt) => {
evt.waitUntil(
caches.open(CACHE_NAME)
.then(cache =>
Promise.all(
FILES.map(url => {
// cache-bust using a random query string
return fetch(`${url}?${Math.random()}`)
.then(response => {
if (!response.ok)
throw Error('Not ok ' + url);
return cache.put(url, response);
});
})
))
.then(() => self.skipWaiting()) // ???
);
});
self.addEventListener('activate', (evt) => {
evt.waitUntil(
caches.keys()
.then(keyList => Promise.all(keyList.map(key => {
if (key !== CACHE_NAME)
return caches.delete(key);
}))
)
.then(() => self.clients.claim()) // ???
);
});
self.addEventListener('fetch', e => {
e.respondWith(
// return from cache if present else fetch
// WARNING: don't use ignoreSearch - extremely slow on Chrome
// https://stackoverflow.com/questions/41758252/service-worker-slow-response-times#41758253
caches.match(e.request)
.then(r => r || fetch(e.request))
);
});