-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserviceworker.js
More file actions
68 lines (63 loc) · 1.86 KB
/
Copy pathserviceworker.js
File metadata and controls
68 lines (63 loc) · 1.86 KB
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
// Hola! This is a ServiceWorker for a digital library PWA template.
// HTML files: try the network first, then the cache.
// Other files: try the cache first, then the network.
// Both: cache a fresh version if possible.
// (beware: the cache will grow and grow; there's no cleanup)
const version = 'diglib-pwa-v1::';
const cacheName = version + 'static';
const offlinePage = './offline.html';
const coreAssets = [
'./',
'./about.html',
'./browse.html',
'./index.html',
'./item.html',
'./map.html',
'./search.html',
'./offline.html',
'./app.js',
'./styles.css',
'./items.json',
'https://unpkg.com/leaflet@1.5.1/dist/leaflet.css',
'https://unpkg.com/leaflet@1.5.1/dist/leaflet.js',
'./manifest.json'
];
addEventListener('install', installEvent => {
skipWaiting();
installEvent.waitUntil(
caches.open(cacheName)
.then( cache => {
//return cache.add(offlinePage);
return cache.addAll(coreAssets);
})
);
});
addEventListener('activate', activateEvent => {
clients.claim();
});
addEventListener('fetch', fetchEvent => {
const request = fetchEvent.request;
if (request.method !== 'GET') {
return;
}
fetchEvent.respondWith(async function() {
const responseFromFetch = fetch(request);
fetchEvent.waitUntil(async function() {
const responseCopy = (await responseFromFetch).clone();
const myCache = await caches.open(cacheName);
await myCache.put(request, responseCopy);
}());
if (request.headers.get('Accept').includes('text/html')) {
try {
return await responseFromFetch;
}
catch(error) {
const responseFromCache = await caches.match(request);
return responseFromCache || caches.match(offlinePage);
}
} else {
const responseFromCache = await caches.match(request);
return responseFromCache || responseFromFetch;
}
}());
});