-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathsw-download-install.js
86 lines (48 loc) · 1.66 KB
/
sw-download-install.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
86
const VERSION = 'v3';
self.addEventListener('install', event => event.waitUntil(installServiceWorker()));
async function installServiceWorker() {
log("Service Worker installation started ");
const cache = await caches.open(getCacheName());
return cache.addAll([
'/',
'carousel.css',
'http://getbootstrap.com/dist/css/bootstrap.min.css',
'https://code.jquery.com/jquery-3.2.1.slim.min.js',
'http://getbootstrap.com/assets/js/vendor/popper.min.js',
'http://getbootstrap.com/dist/js/bootstrap.min.js',
'http://getbootstrap.com/assets/js/vendor/holder.min.js'
]);
}
self.addEventListener('activate', () => activateSW());
async function activateSW() {
log('Service Worker activated');
const cacheKeys = await caches.keys();
cacheKeys.forEach(cacheKey => {
if (cacheKey !== getCacheName() ) {
caches.delete(cacheKey);
}
});
}
self.addEventListener('fetch', event => event.respondWith(cacheThenNetwork(event)));
async function cacheThenNetwork(event) {
const cache = await caches.open(getCacheName());
const cachedResponse = await cache.match(event.request);
if (cachedResponse) {
log('Serving From Cache: ' + event.request.url);
return cachedResponse;
}
const networkResponse = await fetch(event.request);
log('Calling network: ' + event.request.url);
return networkResponse;
}
function getCacheName() {
return "app-cache-" + VERSION;
}
function log(message, ...data) {
if (data.length > 0) {
console.log(VERSION, message, data);
}
else {
console.log(VERSION, message);
}
}