-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice-worker.js
108 lines (96 loc) · 2.39 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// 2017-11-02 16:19
const config = {
version: '20and30',
caches: [
// Main assets
'/',
'/js/index.min.js',
'/css/styles/index.min.css',
'/img/icons.svg',
'/img/favicon.svg',
// Nav menu icons
'/img/adwaita-icons/actions/document-open-recent.svg',
'/img/adwaita-icons/actions/go-top.svg',
'/img/adwaita-icons/actions/view-pin.svg',
'/img/adwaita-icons/places/folder-publicshare.svg',
'/img/octicons/lib/svg/comment-discussion.svg',
'/img/octicons/lib/svg/calendar.svg',
// Logos
'/img/logos/facebook.svg',
'/img/logos/twitter.svg',
'/img/logos/linkedin.svg',
'/img/logos/google-plus.svg',
'/img/logos/reddit.svg',
'/img/logos/gmail.svg',
// Fonts
'/fonts/Alice.woff',
'/fonts/roboto.woff',
'/fonts/ubuntu.woff2',
],
ignored: [
'/service-worker.js',
'/manifest.json',
],
paths: [
'/js/',
'/css/',
'/img/',
'/fonts/',
'/posts/',
],
hosts: [
'secure.gravatar.com',
'i.imgur.com',
'cdn.polyfill.io',
],
};
addEventListener('install', async () => {
const cache = await caches.open(config.version);
await cache.addAll(config.caches);
skipWaiting();
});
addEventListener('activate', event => {
event.waitUntil(async function() {
clients.claim();
}());
});
addEventListener('fetch', async event => {
function isValid(req) {
try {
const url = new URL(req.url);
const isGet = req.method === 'GET';
const allowedHost = config.hosts.includes(url.host);
const isHome = ['/', '/index.html', '/index.php'].some(path => url.pathname === path);
const notIgnored = config.ignored.every(path => url.pathname !== path);
const allowedPath = config.paths.some(path => url.pathname.startsWith(path));
return isGet && (allowedHost || (isHome || (allowedPath && notIgnored)));
} catch(err) {
console.error(err);
return false;
}
}
async function get(request) {
const cache = await caches.open(config.version);
const cached = await cache.match(request);
if (navigator.onLine) {
const fetched = fetch(request).then(async resp => {
if (resp instanceof Response && resp.ok) {
const respClone = await resp.clone();
await cache.put(event.request, respClone);
}
return resp;
});
if (cached instanceof Response) {
return cached;
} else {
const resp = await fetched;
return resp;
}
} else {
return cached;
}
}
if (isValid(event.request)) {
event.respondWith(get(event.request));
}
});