-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-worker.js
85 lines (75 loc) · 2.49 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
75
76
77
78
79
80
81
82
83
84
85
// Progressive Web Application Service Worker
// Move forward for each new update for /service-worker.js?v=${VERSION}
const VERSION = 'v2.6';
var artifacts = [
'/',
'/background.html',
'/favicon.ico?v=1',
'/manifest.json?v=1',
'/css/background.css?v=1',
'/css/main.css?v=16',
'/images/avatar.jpg?v=1',
'/js/scripts.js?v=4',
];
// Clear cache promise
async function clearCache() {
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.filter(cacheName => {
// Return true if you want to remove this cache,
// but remember that caches are shared across
// the whole origin
return cacheName !== VERSION;
}).map(cacheName => {
return caches.delete(cacheName);
})
);
})
};
// 'install' event
self.addEventListener('install', event => {
// #DEBUG
console.log('Installing Service Worker ' + VERSION);
event.waitUntil(
caches.open(VERSION).then(cache => {
return cache.addAll(artifacts);
})
);
event.waitUntil(clearCache());
});
// 'activate' event
// 1. Clear old caches
self.addEventListener('activate', event => {
// #DEBUG
console.log('Activating Service Worker ' + VERSION);
event.waitUntil(clearCache());
});
// 'fetch' event
self.addEventListener('fetch', event => {
//
event.respondWith(caches.match(event.request).then(response => {
// Cache hit - return response
if (response) {
return response;
}
// Fetch through network
return fetch(event.request).then(response => {
// #DEBUG
// console.log(event.request);
// console.log(response);
// Check if we received a valid response
if (!response || response.status !== 200 || response.type !== 'basic') {
return response;
}
// IMPORTANT: Clone the response. A response is a stream
// and because we want the browser to consume the response
// as well as the cache consuming the response, we need
// to clone it so we have two streams.
var responseToCache = response.clone();
caches.open(VERSION).then(cache => {
cache.put(event.request, responseToCache);
});
return response;
});
}));
});