-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
72 lines (65 loc) · 2.05 KB
/
Copy pathsw.js
File metadata and controls
72 lines (65 loc) · 2.05 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
69
70
71
72
/*
* sw.js - Service worker for the Tasks PWA.
*
* Caches the static app shell so the app loads instantly and works offline.
* CalDAV traffic (cross-origin, and non-GET) is never intercepted — those
* requests fall through to the network so live sync behaves normally.
*
* Bump CACHE_VERSION whenever the app shell changes to roll the cache.
*/
const CACHE_VERSION = 'v6';
const CACHE_NAME = 'tasklist-' + CACHE_VERSION;
const APP_SHELL = [
'./',
'./index.html',
'./css/styles.css',
'./js/ical.js',
'./js/caldav.js',
'./js/app.js',
'./manifest.webmanifest',
'./icons/icon.svg',
'./icons/icon-192.png',
'./icons/icon-512.png',
'./icons/apple-touch-icon.png',
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME)
.then((cache) => cache.addAll(APP_SHELL))
.then(() => self.skipWaiting())
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys()
.then((keys) => Promise.all(
keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k))
))
.then(() => self.clients.claim())
);
});
self.addEventListener('fetch', (event) => {
const req = event.request;
const url = new URL(req.url);
// Only handle same-origin GET requests (the app shell). Let everything
// else — notably CalDAV requests to the calendar server — pass straight
// through to the network untouched.
if (req.method !== 'GET' || url.origin !== self.location.origin) return;
event.respondWith(staleWhileRevalidate(req));
});
// Serve from cache immediately, refresh the cache entry in the background.
function staleWhileRevalidate(req) {
return caches.open(CACHE_NAME).then((cache) =>
cache.match(req).then((cached) => {
const network = fetch(req)
.then((resp) => {
if (resp && resp.status === 200 && resp.type === 'basic') {
cache.put(req, resp.clone());
}
return resp;
})
.catch(() => cached); // offline: fall back to whatever we have
return cached || network;
})
);
}