-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
111 lines (90 loc) · 2.64 KB
/
Copy pathsw.js
File metadata and controls
111 lines (90 loc) · 2.64 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
const CACHE_VERSION = "v1";
const CACHE_NAME = `mainroute-caches-${CACHE_VERSION}`;
const OFFLINE_URL = "/offline.html";
const CORE_ASSETS = [
OFFLINE_URL,
"/src/social-.png",
"/src/social_.png",
"/css/index.css",
"/js/index.js",
"/favicon.ico",
"/index.html",
"/manifest.webmanifest",
];
self.addEventListener("install", (event) => {
self.skipWaiting();
event.waitUntil(
(async () => {
const cache = await caches.open(CACHE_NAME);
await Promise.allSettled(
CORE_ASSETS.map((asset) => cache.add(asset))
);
})()
);
});
self.addEventListener("activate", (event) => {
event.waitUntil(
(async () => {
const cacheNames = await caches.keys();
await Promise.all(
cacheNames
.filter((name) => name !== CACHE_NAME)
.map((name) => caches.delete(name))
);
if ("navigationPreload" in self.registration) {
await self.registration.navigationPreload.enable();
}
await self.clients.claim();
})()
);
});
self.addEventListener("fetch", (event) => {
const { request } = event;
if (request.method !== "GET") return;
// HTML pages: Network First
if (
request.mode === "navigate" ||
request.headers.get("accept")?.includes("text/html")
) {
event.respondWith(networkFirst(request));
return;
}
// CSS, JS, Images, Fonts: Stale While Revalidate
if (
["style", "script", "image", "font"].includes(
request.destination
)
) {
event.respondWith(staleWhileRevalidate(request));
return;
}
});
async function networkFirst(request) {
try {
const preload = await event?.preloadResponse;
if (preload) return preload;
const response = await fetch(request);
if (response.ok) {
const cache = await caches.open(CACHE_NAME);
cache.put(request, response.clone());
}
return response;
} catch {
const cached = await caches.match(request);
if (cached) return cached;
return caches.match(OFFLINE_URL);
}
}
async function staleWhileRevalidate(request) {
const cache = await caches.open(CACHE_NAME);
const cached = await cache.match(request);
const networkFetch = fetch(request)
.then((response) => {
if (response.ok) {
cache.put(request, response.clone());
}
return response;
})
.catch(() => null);
return cached || networkFetch;
}