Newer
Older
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
66
self.addEventListener("install", (event) => {
console.info("Service worker installed.", event)
})
self.addEventListener("activate", (event) => {
console.info("Service worker activated.", event)
})
const CACHE_NAME = "APP-V0"
const FILES_TO_CACHE = [
"/index.html",
"/js/app.js",
"/manifest.json",
]
const FILE_ALIASES = new Map([
["/", "/index.html"]
])
const normalizeUrl = (url) => {
const url_ = new URL(url)
url_.pathname = url_.pathname.replace(/\/+/g, "/").replace(/\/$/, "")
if (FILE_ALIASES.has(url_.pathname)) {
url_.pathname = FILE_ALIASES.get(url_.pathname)
}
return url_.href
}
self.addEventListener("install", async (event) => {
const cache = await caches.open(CACHE_NAME)
const additions = cache.addAll(FILES_TO_CACHE)
await additions
console.info(`Files cached: [\n ${FILES_TO_CACHE.join(`,\n `)}\n]`)
})
self.addEventListener("activate", async (event) => {
const oldCacheKeys = (await caches.keys()).filter((key) => key != CACHE_NAME)
oldCacheKeys.forEach((key) => caches.delete(key))
})
self.addEventListener("fetch", (event) => {
const normalizedUrl = normalizeUrl(event.request.url)
let response = fetch(event.request)
if (FILES_TO_CACHE.includes(normalizedUrl)) {
response = response
.then(async (response) => {
const cache = await caches.open(CACHE_NAME)
await cache.put(normalizedUrl, response.clone())
return response
})
.catch(() => caches.match(normalizedUrl))
.catch(e => null)
}
event.respondWith(
fetch(event.request)
.then(async (response) => {
if (FILES_TO_CACHE.includes(new URL(normalizedUrl).pathname)) {
const cache = await caches.open(CACHE_NAME)
await cache.put(normalizedUrl, response.clone())
}
return response
})
.catch(() => caches.match(normalizedUrl))
.catch(e => null)
)
})