-
Notifications
You must be signed in to change notification settings - Fork 1
/
service-worker.js
48 lines (43 loc) · 1.21 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
//code primarily from codelab
//Apache 2.0 licnense
const CACHE_NAME = 'static-cache-v1';
const FILES_TO_CACHE = [
'index.html', 'source.js', 'style.css'
];
self.addEventListener('install', (evt) => {
evt.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll(FILES_TO_CACHE);
})
);
self.skipWaiting();
});
self.addEventListener('activate', (evt) => {
evt.waitUntil(
caches.keys().then((keyList) => {
return Promise.all(keyList.map((key) => {
if (key !== CACHE_NAME) {
return caches.delete(key);
}
}));
})
);
self.clients.claim();
});
self.addEventListener('fetch', (evt) => {
evt.respondWith(
caches.open(DATA_CACHE_NAME).then((cache) => {
return fetch(evt.request)
.then((response) => {
// If the response was good, clone it and store it in the cache.
if (response.status === 200) {
cache.put(evt.request.url, response.clone());
}
return response;
}).catch((err) => {
// Network request failed, try to get it from the cache.
return cache.match(evt.request);
});
}));
return;
});