-
Notifications
You must be signed in to change notification settings - Fork 0
/
serviceworker.js
38 lines (35 loc) · 1.21 KB
/
serviceworker.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
// Licensed under a CC0 1.0 Universal (CC0 1.0) Public Domain Dedication
// http://creativecommons.org/publicdomain/zero/1.0/
// 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 cacheName = 'files';
addEventListener('fetch', fetchEvent => {
const request = fetchEvent.request;
const shouldLog = false;
if (request.method !== 'GET') {
return;
}
fetchEvent.respondWith(async function() {
const fetchPromise = fetch(request);
fetchEvent.waitUntil(async function() {
const responseFromFetch = await fetchPromise;
const responseCopy = responseFromFetch.clone();
if (!responseCopy.ok) return;
const myCache = await caches.open(cacheName);
return myCache.put(request, responseCopy);
}());
if (request.headers.get('Accept').includes('text/html')) {
try {
return await fetchPromise;
}
catch(error) {
return caches.match(request);
}
} else {
const responseFromCache = await caches.match(request);
return responseFromCache || fetchPromise;
}
}());
});