-
Notifications
You must be signed in to change notification settings - Fork 18
/
service-worker.js
66 lines (59 loc) · 1.7 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
const cachePrefix = 'mission-03';
function fetchFromCache (request) {
return caches.match(request).then(response => {
if (!response) {
throw Error(`${request.url} not found in cache`);
}
return response;
});
}
function addToCache (request, response) {
if (response.ok) {
const copy = response.clone();
caches.open(`${cachePrefix}-assets`).then(cache => {
cache.put(request, copy);
});
}
return response;
}
function offlinePage () {
return caches.open(`${cachePrefix}-offline`).then(cache => {
return cache.match('offline.html');
});
}
function isNavigateRequest (request) {
return (request.mode === 'navigate' ||
(request.method === 'GET' &&
request.headers.get('accept').includes('text/html')));
}
function isImageRequest (request) {
return (request.headers.get('Accept').indexOf('image') !== -1);
}
self.addEventListener('install', event => {
const offlineURL = 'offline.html';
event.waitUntil(
fetch(new Request(offlineURL)).then(response => {
return caches.open(`${cachePrefix}-offline`).then(cache => {
return cache.put(offlineURL, response);
});
})
);
});
self.addEventListener('fetch', event => {
var request = event.request;
if (isNavigateRequest(request)) {
event.respondWith(
fetch(request)
.then(response => addToCache(request, response))
.catch(() => fetchFromCache(request))
.catch(() => offlinePage())
);
} else if (isImageRequest(request)) {
event.respondWith(
fetchFromCache(request)
.catch(() => fetch(request)
.then(response => addToCache(request, response)))
.catch(() => console.log('unable to respond to request'))
);
}
});