-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-worker.js
65 lines (57 loc) · 2.02 KB
/
service-worker.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
// change static cache name after the app changed
const staticCacheName = 'dabravesce-sw-v2'
const dynamicCacheName = 'dabravesce-sw-d-v2'
const assetsToCache = [
'.', // or 'index.html' | ?i=0-0-0-0
'scripts/app.js',
'styles/main.css',
'tomes/contact-data.js',
'tomes/new-testament-searchable.js',
'tomes/new-testament.js',
'tomes/prayer-book.js',
'tomes/songs.js'
]
self.addEventListener('install', async () => {
const cache = await caches.open(staticCacheName)
await cache.addAll(assetsToCache)
})
// uncomment when app changed
// self.addEventListener('activate', async event => {
// const cacheNames = await caches.keys()
// // delete all SW cached versions except for the current one
// await Promise.all(
// cacheNames
// .filter(name => name !== staticCacheName)
// .filter(name => name !== dynamicCacheName)
// .map(name => caches.delete(name))
// )
// })
self.addEventListener('fetch', event => {
const { request } = event
event.respondWith(cacheFirst(request))
// console.log(event.request.url)
// const { request } = event
// const url = new URL(request.url)
// if (url.origin === location.origin) {
// event.respondWith(cacheFirst(request))
// } else {
// event.respondWith(networkFirst(request))
// }
})
async function cacheFirst(request) {
const cachedResponse = await caches.match(request).response // .response
return cachedResponse ?? await fetch(request) // fetch if chached nothing
}
// async function networkFirst(request) {
// const cache = await caches.open(dynamicCacheName)
// try {
// const response = await fetch(request)
// await cache.put(request, response.clone())
// return response
// } catch (e) {
// const cached = await cache.match(request)
// return cached ?? caches.match('offline.html')
// // ?? when there is no network and cache is empty
// // offline.html is a file to create
// }
// }