-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcacher.js
47 lines (40 loc) · 1.08 KB
/
cacher.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
const CACHE_NAME = 'blog'
const NETWORK_TIMEOUT = 1000
const URLS_TO_CACHE = [
'/',
'/index.html',
'/assets/css/main.css',
'/assets/js/script.js',
'/assets/header-background.jpeg',
'/assets/favicons/favicon-96x96.png',
]
this.addEventListener('install', event => {
event.waitUntil(initialCache())
})
this.addEventListener('fetch', event => {
event.respondWith(fromNetwork(event.request)
.catch(() => fromCache(event.request)))
})
function initialCache() {
caches.open(CACHE_NAME).then(cache => {
return cache.addAll(URLS_TO_CACHE)
})
}
function fromNetwork(request, failover) {
let networkTimeoutError = setTimeout(() => console.log('No connection'), NETWORK_TIMEOUT)
return (fetch(request).then(response => {
clearTimeout(networkTimeoutError)
return Promise.resolve(response)
}).catch(() => Promise.reject()))
}
function fromCache(request) {
caches.open(CACHE_NAME).then(cache => {
return cache.match(request).then(result => {
if (result) {
return result
} else {
return Promise.reject('No matches')
}
})
})
}