-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
49 lines (42 loc) · 1.33 KB
/
sw.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
const staticCacheName = "s-app-v1";
const dynamicCacheName = "d-app-v1";
const assetUrls = ["index.html", "/js/app.js", "/css/styles.css"];
self.addEventListener("install", async (event) => {
// console.log("install");
const cache = await caches.open(staticCacheName);
await cache.addAll(assetUrls);
});
self.addEventListener("activate", async (event) => {
// console.log("activate");
const cacheNames = await caches.keys();
await Promise.all(
cacheNames
.filter((name) => name !== staticCacheName)
.filter((name) => name !== dynamicCacheName)
.map((name) => caches.delete(name))
);
});
self.addEventListener("fetch", (event) => {
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 cached = await caches.match(request);
return cached ?? (await fetch(request));
}
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 ?? (await caches.match("/offline.html"));
}
}