-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsw.js
56 lines (53 loc) · 1.42 KB
/
sw.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
const filesToCache = ['./', './index.html']
const cacheName = 'ebook'
const version = '0.0.1'
// install
self.addEventListener('install', (event) => {
console.log('installing…')
self.skipWaiting();
event.waitUntil(
caches.open(cacheName).then((cache) => {
console.log('Caching app ok')
return cache.addAll(filesToCache)
})
)
})
// activate
self.addEventListener('activate', (event) => {
console.log('now ready to handle fetches!')
event.waitUntil(
caches.keys().then(function (cacheNames) {
var promiseArr = cacheNames.map(function (item) {
if (item !== cacheName) {
// Delete that cached file
console.log(
'[ServiceWorker] Removing Cached Files from Cache - ',
item
)
return caches.delete(item)
}
})
return Promise.all(promiseArr)
})
) // end event.waitUntil
})
// fetch
self.addEventListener('fetch', (event) => {
const tryFetch = fetch(event.request).then(
(res) => {
var clone = res.clone()
caches.open(cacheName).then(function (cache) {
cache.put(event.request, clone)
})
return res
}
)
const promise = caches.match(event.request).then(cached => {
return tryFetch.catch((err) => {
if(!cached) throw err
console.warn('[ServiceWorker] Network Error! resource serve from cache.')
return cached
})
})
event.respondWith(promise);
})