-
Notifications
You must be signed in to change notification settings - Fork 0
/
serviceWorker.js
48 lines (41 loc) · 1.32 KB
/
serviceWorker.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
const cacheName = 'v1';
self.addEventListener('install', (event) => {
// console.log('Service Worker: Installed ')
})
self.addEventListener('activate', (event) => {
// console.log('Service Worker: Activated ')
// Remove unwanted caches
event.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)
}
})
)
})
)
})
self.addEventListener('fetch', (event) => {
// console.log('Service Worker: Fetching ')
event.respondWith(
fetch(event.request)
.then(res => {
// Make copy/clone of respnse
const resClone = res.clone()
// Open Cache
caches
.open(cacheName)
.then(cache => {
// Add response to cache
cache.put(event.request, resClone)
})
return res
})
.catch(err => caches.match(event.request)
.then(res => res))
)
})