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
|
const CACHE_NAME = 'offline-cache-v1'
const ASSETS = [
'/',
'/index.html',
'/styles.css',
'/styles3.css',
'/tempo.md',
'/bell.png',
'/bell.svg',
'/by-sa.png',
'/cc-by-sa-legalcode.txt',
'/symbols.txt'
]
self.addEventListener('install', e => {
console.log('installing sw')
e.waitUntil(caches.open(CACHE_NAME).then(cache => cache.addAll(ASSETS)))
self.skipWaiting()
})
self.addEventListener('activate', e => {
console.log('sw activated')
e.waitUntil(self.clients.claim())
})
self.addEventListener('fetch', e => {
const url = new URL(e.request.url)
const isTarget = ASSETS.includes(url.pathname) || url.pathname.startsWith('/fonts/')
if (!isTarget) return
e.respondWith(
caches.open(CACHE_NAME).then(async cache => {
const cachedResponse = await cache.match(e.request)
if (cachedResponse) console.log(`cache ${url.pathname}`)
else console.log(`fetch ${url.pathname}`)
const networkFetch = fetch(e.request).then(networkResponse => {
if (networkResponse.ok) {
console.log(`updating ${url.pathname}`)
cache.put(e.request, networkResponse.clone())
}
return networkResponse
}).catch(err => {
console.error(`failed ${url.pathname}:`, err)
})
return cachedResponse || networkFetch
})
)
})
|