forked from eirikb/stfu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
50 lines (43 loc) · 1.18 KB
/
sw.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
const cacheName = 'stfu_2';
const urlsToCache = [
'/',
'https://opencache.statkart.no/gatekeeper/gk/',
];
function responseIsOk(response) {
return response.ok && response.status >= 200 && response.status <= 299;
}
self.addEventListener('install', event =>
event.waitUntil(
caches.open(cacheName).then(cache =>
cache.addAll(urlsToCache)
)
)
);
function fetchAndCache(request) {
return fetch(request).then(response => {
const responseToCache = response.clone();
if (request.method === 'GET' && responseIsOk(response)) {
caches.open(cacheName).then(cache =>
cache.put(request, responseToCache)
);
}
return response;
}
);
}
function mapTilesFromCacheRestFromOnlineOrCacheIfOffline(request) {
if (request.url.match(/gatekeeper/i)) {
return caches.match(request).then(response => {
if (response && responseIsOk(response)) {
return response;
}
return fetchAndCache(request);
});
}
return fetchAndCache(request).catch(() => caches.match(request));
}
self.addEventListener('fetch', event =>
event.respondWith(
mapTilesFromCacheRestFromOnlineOrCacheIfOffline(event.request)
)
);