-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-worker.js
71 lines (63 loc) · 1.83 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
const CONFIG = {
cacheName: 'hackernews-feed',
apiURL: 'hacker-news.firebaseio.com',
staticFiles: [
'./',
'./manifest.json',
'./index.html',
'./main.js',
'./style.css',
'./icon/favicon.ico',
'./icon/16.png',
'./icon/32.png',
'./icon/192.png',
'./icon/180.png',
'./icon/512.png'
]
};
this.addEventListener('install', (e) => {
console.info('[ServiceWorker] Install');
e.waitUntil(
caches.open(CONFIG.cacheName).then((cache) => {
console.info('[ServiceWorker] Caching static files');
return cache.addAll(CONFIG.staticFiles);
})
);
});
this.addEventListener('activate', (e) => {
console.info('[ServiceWorker] Activate');
e.waitUntil(
// eslint-disable-next-line array-callback-return,consistent-return
caches.keys().then((keyList) => Promise.all(keyList.map((key) => {
if (key !== CONFIG.cacheName) {
console.info('[ServiceWorker] Removing old cache: ', key);
return caches.delete(key);
}
})))
);
// runs SW instantly in any existing tab previously from SW activation
// eslint-disable-next-line no-restricted-globals
return self.clients.claim();
});
self.addEventListener('fetch', function(e) {
console.log('[Service Worker] Fetch', e.request.url);
const isApiRequest = e.request.url.indexOf(CONFIG.apiURL) > -1;
if (isApiRequest) {
// get network response, cache and return it
e.respondWith(
caches.open(CONFIG.cacheName).then(function(cache) {
return fetch(e.request).then(function(response){
cache.put(e.request.url, response.clone());
return response;
});
})
);
} else {
// deliver from cache, if not available, request it
e.respondWith(
caches.match(e.request).then(function(response) {
return response || fetch(e.request);
})
);
}
});