-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw_cached_site.js
40 lines (37 loc) · 1.08 KB
/
sw_cached_site.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
const cacheName = 'v2';
// Call install event
self.addEventListener('install', e => {
console.log('installed');
});
self.addEventListener('activate', e => {
console.log('activate');
// Remove unwanted cache
e.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cache => {
if (cache !== cacheName) {
console.log('sw clearing old cache');
return caches.delete(cache);
}
})
)
})
);
});
// Call fetch event
self.addEventListener('fetch', e => {
console.log('sw fetching');
e.respondWith(
fetch(e.request).then(res => {
// Make copy/clone fo response
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))
);
})