forked from PlytonRexus/if-script
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice-worker.js
71 lines (62 loc) · 1.92 KB
/
service-worker.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
let CACHE_VERSIONS = {
'css': 1,
'terp': 1,
'fonts': 2,
'images': 1
};
let CURRENT_CACHES = {};
let addrs = {
css: ['css/index.css', 'downloadable/if_r.css'],
fonts: ['assets/fonts/FiraMono-Regular.ttf', 'assets/fonts/VarelaRound-Regular.ttf'],
images: ['assets/images/book-background0.jpg', 'assets/images/if-logo.png']
};
let props = Object.keys(CACHE_VERSIONS);
props.forEach(val => {
CURRENT_CACHES[val] = `${val}-v${CACHE_VERSIONS[val]}`;
});
self.addEventListener('install', (event) => {
event.waitUntil(
props.forEach(prop => {
caches
.open(CURRENT_CACHES[prop])
.then(cache => {
Object.keys(addrs).forEach(val => {
val.forEach(addr => {
cache.add(addr);
});
});
})
.catch(e => console.log(e))
})
);
});
self.addEventListener('fetch', function (event) {
let preTypes = [/\/js\//, /\/css\//, /\/images\//, /\/fonts\//];
let index = preTypes.findIndex(preType => {
if (event.request.url.match(preType))
return true;
else return false;
});
let prop = 'css';
if (index !== -1)
prop = event.request.url.match(preTypes[index])[0].replace(/\//g, "");
event.respondWith(
caches.open(CURRENT_CACHES[prop]).then(function (cache) {
return cache.match(event.request).then(function (response) {
if (response) {
return response;
}
return fetch(event.request.clone()).then(function (response) {
if (response.status < 400 &&
response.url &&
response.url.match(new RegExp(prop, 'i'))) {
cache.put(event.request, response.clone());
}
return response;
}).catch(e => console.log("Why not?", e));
}).catch(function (error) {
throw error;
});
})
);
});