-
Notifications
You must be signed in to change notification settings - Fork 3
/
service_worker.js
59 lines (54 loc) · 1.6 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
const cacheKey = 'v4';
console.log(`cacheKey = [${cacheKey}]`);
this.addEventListener('install', evt => {
console.log('installed');
evt.waitUntil(
caches.open(cacheKey).then(cache => {
return cache.addAll([
'.',
'manifest.webmanifest',
'index.html',
'coscup.jpg',
]);
}));
});
this.addEventListener('fetch', evt => {
evt.respondWith(
caches.open(cacheKey).then(cache => {
return cache.match(evt.request).then(resp => {
if (resp) {
console.log(`Using cached [${evt.request.url}]`);
return resp;
}
console.log(`Fetching [${evt.request.url}] from remote`);
return fetch(evt.request).then(remoteResp => {
if (evt.request.url.match(/cdn/i))
cache.put(evt.request, remoteResp.clone());
return remoteResp;
});
});
}));
});
this.addEventListener('activate', evt => {
console.log('activated');
evt.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.filter(cacheName => cacheName != cacheKey)
.map(cacheName => caches.delete(cacheName)))
}).then(() => self.clients.claim()));
});
this.addEventListener('message', evt => {
if (evt.data.action == 'purgeCache') {
console.log(`Purging caches...`);
caches.keys().then(cacheNames => {
return Promise.all(cacheNames.map(cacheName => {
console.log(`Cache [${cacheName}] deleted`);
return caches.delete(cacheName);
}));
}).then(() => {
console.log('Caches purged');
evt.ports[0].postMessage({ok: true})
});
}
});