-
Notifications
You must be signed in to change notification settings - Fork 4
/
sw.js
88 lines (76 loc) · 2.61 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
importScripts("/precache-manifest.d1df9d2220f6553b1dd180249bc4b80b.js", "https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js");
const CACHE_VERSION = 'v10';
const initialCache = [
'/',
'/index.html',
'https://fonts.googleapis.com/css?family=Advent+Pro:500,600,700',
'https://fonts.googleapis.com/css?family=Nunito:300,400,600,700',
]
.concat(self.__precacheManifest.map(item => item.url))
.map(url => new Request(url, { redirect: 'follow' }));
const isAsset = url => url.match(/(\/assets\/.*$|fonts\.(googleapis|gstatic))|\.css$|\.js$/);
const isDocument = url => url.match(/\/documents\//);
const isGoogleResource = url => url.match(/fonts|google/);
const isTemplate = url =>
!isDocument(url) && !isAsset(url) && !isGoogleResource(url)
&& !url.endsWith('/') && !url.endsWith('.json') && !url.toLowerCase().endsWith('.md');
function onInstall(event) {
console.log('Service Worker registered');
event.waitUntil(
caches.open(CACHE_VERSION).then(cache => {
cache.addAll(initialCache);
})
);
}
self.addEventListener('install', onInstall);
function onFetch(event) {
event.respondWith(
caches.open(CACHE_VERSION).then(cache => {
if (isAsset(event.request.url)) {
return retrieveFromCache({ event, cache })
.catch(fetchAndCache)
}
return fetchAndCache({ event, cache })
.catch((() => retrieveFromCache({ event, cache })));
})
)
}
function fetchAndCache({ event, cache }) {
console.log(`Adding resource ${event.request.url} to the cache.`);
let url = event.request.url;
if (isTemplate(url)) {
url = url.concat('/');
}
const request = new Request(
url,
{credentials: !url.includes('fonts') ? event.request.credentials : 'omit', redirect: 'follow' }
);
return fetch(request)
.then(response => {
if (response.ok) {
cache.add(request);
return response;
}
console.log(`Fetch for resource ${event.request.url} was not 200 OK`);
return Promise.reject()
});
}
function retrieveFromCache({ event, cache }) {
let request = event.request;
if (isTemplate(event.request.url)) {
const url = event.request.url + '/';
request = new Request(
url,
{credentials: !url.includes('fonts') ? event.request.credentials : 'omit', redirect: 'follow' }
);
}
return cache.match(request).then(request => {
if (request) {
console.log(`Resource ${request.url} retrieved from cache`);
return request;
}
console.log(`Resource ${event.request.url} not in cache.`);
return Promise.reject({ event, cache });
})
}
self.addEventListener('fetch', onFetch);