-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.template.js
More file actions
49 lines (38 loc) · 1.25 KB
/
sw.template.js
File metadata and controls
49 lines (38 loc) · 1.25 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
const CACHE_NAME = 'head_hurts_<%= version %>'
const CACHE_ASSETS = JSON.parse('<%- cache %>')
addEventListener('activate', (event) => {
async function activate () {
const cacheNames = await caches.keys()
const deletePromises = cacheNames
.filter((key) => key !== CACHE_NAME)
.map((key) => caches.delete(key))
await Promise.all(deletePromises)
}
event.waitUntil(activate())
})
addEventListener('install', (event) => {
async function install () {
const cache = await caches.open(CACHE_NAME)
await cache.addAll(CACHE_ASSETS)
}
event.waitUntil(install())
})
addEventListener('fetch', (event) => {
async function handleFetch () {
const url = event.request.mode === 'navigate' ? '<%= env.BASE_URL %>' : event.request.url
const cache = await caches.open(CACHE_NAME)
const response = await cache.match(url)
return response || fetch(event.request.url)
}
const apiUrls = ['<%= env.DATABASE_PROXY %>', 'api/']
const ignoreCache = apiUrls.some((url) => event.request.url.includes(url))
if (event.request.method !== 'GET' || ignoreCache) {
return null
}
event.respondWith(handleFetch())
})
addEventListener('message', (event) => {
if (event.data.action === 'skipWaiting') {
self.skipWaiting()
}
})