-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsw.js
More file actions
73 lines (65 loc) · 1.57 KB
/
sw.js
File metadata and controls
73 lines (65 loc) · 1.57 KB
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
var cacheName = 'calci-cache';
var cacheAssets = [
'/index.html',
'/style.css',
'/script.js',
];
// Call install Event
self.addEventListener('install', e => {
// Wait until promise is finished
e.waitUntil(
caches.open(cacheName)
.then(cache => {
console.log(`Service Worker: Caching Files: ${cache}`);
cache.addAll(cacheAssets)
// When everything is set
.then(() => self.skipWaiting())
})
);
})
// Call Activate Event
self.addEventListener('activate', e => {
console.log('Service Worker: Activated');
// Clean up old caches by looping through all of the
// caches and deleting any old caches or caches that
// are not defined in the list
e.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(
cache => {
if (cache !== cacheName) {
console.log('Service Worker: Clearing Old Cache');
return caches.delete(cache);
}
}
)
)
})
);
})
var cacheName = 'calci-cache';
// Call Fetch Event
self.addEventListener('fetch', e => {
console.log('Service Worker: Fetching');
e.respondWith(
fetch(e.request)
.then(res => {
// The response is a stream and in order the browser
// to consume the response and in the same time the
// cache consuming the response it needs to be
// cloned in order to have two streams.
const resClone = res.clone();
// Open cache
caches.open(cacheName)
.then(cache => {
// Add response to cache
cache.put(e.request, resClone);
});
return res;
}).catch(
err => caches.match(e.request)
.then(res => res)
)
);
});