Repository navigation
Expand file tree
/
Copy pathsw.js
More file actions
52 lines (48 loc) · 1.7 KB
/
Copy pathsw.js
File metadata and controls
52 lines (48 loc) · 1.7 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
/* Sticky Notes service worker — app shell caching for offline use.
Bump CACHE_VERSION whenever css/js/html changes ship. */
const CACHE_VERSION = 'sticky-notes-v3';
const APP_SHELL = [
'./',
'./index.html',
'./css/styles.css',
'./javascript/script.js',
'./manifest.webmanifest',
'./assets/icon.svg'
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_VERSION)
.then((cache) => cache.addAll(APP_SHELL))
.then(() => self.skipWaiting())
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys()
.then((keys) => Promise.all(
keys.filter((key) => key !== CACHE_VERSION).map((key) => caches.delete(key))
))
.then(() => self.clients.claim())
);
});
// Stale-while-revalidate: serve from cache instantly, refresh the cache in the
// background so the next visit picks up deployed changes.
self.addEventListener('fetch', (event) => {
const { request } = event;
if (request.method !== 'GET') return;
if (!request.url.startsWith('http')) return;
event.respondWith(
caches.open(CACHE_VERSION).then(async (cache) => {
const cached = await cache.match(request, { ignoreSearch: true });
const network = fetch(request)
.then((response) => {
if (response && response.ok && (response.type === 'basic' || response.type === 'cors')) {
cache.put(request, response.clone());
}
return response;
})
.catch(() => cached);
return cached || network;
})
);
});