-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathsw.js
More file actions
65 lines (60 loc) · 1.56 KB
/
sw.js
File metadata and controls
65 lines (60 loc) · 1.56 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
const CACHE_NAME = 'rfcfyi-v1773719669'
const STATIC_ASSETS = [
'/',
'/index.html',
'/client.js',
'/data.js',
'/util.js',
'/style.css',
'/rfcfyi.png',
'/manifest.json'
]
const DATA_ASSETS = [
'/var/tags.json',
'/var/rfcs.json',
'/var/refs.json'
]
self.addEventListener('install', (event) => {
self.skipWaiting()
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
console.log('[SW] Pre-caching static and data assets')
return cache.addAll([...STATIC_ASSETS, ...DATA_ASSETS])
})
)
})
self.addEventListener('activate', (event) => {
event.waitUntil(
Promise.all([
self.clients.claim(),
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cacheName) => {
if (cacheName !== CACHE_NAME) {
console.log('[SW] Removing old cache', cacheName)
return caches.delete(cacheName)
}
})
)
})
])
)
})
self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url)
// Handle data and static assets with Stale-While-Revalidate
event.respondWith(
caches.open(CACHE_NAME).then(async (cache) => {
const cachedResponse = await cache.match(event.request)
const fetchPromise = fetch(event.request).then((networkResponse) => {
if (networkResponse.ok) {
cache.put(event.request, networkResponse.clone())
}
return networkResponse
}).catch(() => {
return cachedResponse
})
return cachedResponse || fetchPromise
})
)
})