forked from trys/clock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
97 lines (85 loc) · 2.88 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
88
89
90
91
92
93
94
95
96
97
/*
This is a modified version of Ethan Marcotte's service worker (https://ethanmarcotte.com/theworkerofservices.js),
which is in turn a modified version of Jeremy Keith's service worker (https://adactio.com/serviceworker.js),
with a few additional edits borrowed from Filament Group's. (https://www.filamentgroup.com/sw.js)
*/
(function() {
const version = 'v2';
const cacheName = ':clock:';
const staticCacheName = version + cacheName + 'static';
const pagesCacheName = cacheName + 'pages';
const staticAssets = ['/', '/main.js', '/style.css', '/ding.mp3'];
function updateStaticCache() {
// These items must be cached for the Service Worker to complete installation
return caches.open(staticCacheName).then(cache => {
return cache.addAll(
staticAssets.map(url => new Request(url, { credentials: 'include' }))
);
});
}
function stashInCache(cacheName, request, response) {
caches.open(cacheName).then(cache => cache.put(request, response));
}
// Remove caches whose name is no longer valid
function clearOldCaches() {
return caches.keys().then(keys => {
return Promise.all(
keys
.filter(key => key.indexOf(version) !== 0)
.map(key => caches.delete(key))
);
});
}
self.addEventListener('install', event => {
event.waitUntil(updateStaticCache().then(() => self.skipWaiting()));
});
self.addEventListener('activate', event => {
event.waitUntil(clearOldCaches().then(() => self.clients.claim()));
});
self.addEventListener('fetch', event => {
const request = event.request;
const url = new URL(request.url);
const allowedUrls = [
'https://count-down-clock.netlify.com',
'https://clock.clearleft.com',
'http://localhost:4321'
];
if (!allowedUrls.find(x => url.href.startsWith(x))) return;
if (request.method !== 'GET') return;
if (url.href.indexOf('?') !== -1) return;
if (request.headers.get('Accept').includes('text/html')) {
event.respondWith(
fetch(request)
.then(response => {
let copy = response.clone();
if (
staticAssets.includes(url.pathname) ||
staticAssets.includes(url.pathname + '/')
) {
stashInCache(staticCacheName, request, copy);
} else {
stashInCache(pagesCacheName, request, copy);
}
return response;
})
.catch(() => {
// CACHE or FALLBACK
return caches
.match(request)
.then(response => response || caches.match('/'));
})
);
return;
}
event.respondWith(
fetch(request)
.then(response => response)
.catch(() => {
return caches
.match(request)
.then(response => response)
.catch(console.error);
})
);
});
})();