blob: ddab607e62de145b00d62b2d069452a8ab2b1766 (
plain)
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
|
const CACHE_NAME = 'v1.2.5'; // Per-version requests cache
const IMAGES_CACHE_NAME = 'images' // Long-term images cache
const isS3Url = url => url.includes('amazonaws.com');
this.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => cache.addAll(['index.html']))
.catch(e => console.log(e))
);
})
this.addEventListener('fetch', event => {
if (isS3Url(event.request.url)) {
event.respondWith(
caches.open(IMAGES_CACHE_NAME)
.then(cache => cache.match(event.request)
.then(match => match || fetch(event.request)
.then(response => {
cache.put(event.request, response.clone());
return response;
})
)
.catch(e => console.log(`Error ${e}`))
)
);
} else {
event.respondWith(
caches.open(CACHE_NAME)
.then(cache => fetch(event.request)
.then(response => {
cache.put(event.request, response.clone());
return response;
})
.catch(() => cache.match(event.request))
)
);
}
});
this.addEventListener('activate', event => {
const cacheWhiteList = [CACHE_NAME];
event.waitUntil(
caches.keys()
.then(keys => Promise.all(
keys.map(key => {
if (cacheWhiteList.indexOf(key) === -1) return caches.delete(key);
})
))
);
});
|