-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsw.js
40 lines (36 loc) · 1.14 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
const cacheName = "offline-cache-v1";
const cacheUrls = ["index.html", "cat.jpeg"];
// Installing the Service Worker
self.addEventListener("install", async (event) => {
try {
const cache = await caches.open(cacheName);
await cache.addAll(cacheUrls);
} catch (error) {
console.error("Service Worker installation failed:", error);
}
});
// Fetching resources
self.addEventListener("fetch", (event) => {
event.respondWith(
(async () => {
const cache = await caches.open(cacheName);
try {
const cachedResponse = await cache.match(event.request);
if (cachedResponse) {
console.log("cachedResponse: ", event.request.url);
return cachedResponse;
}
const fetchResponse = await fetch(event.request);
if (fetchResponse) {
console.log("fetchResponse: ", event.request.url);
await cache.put(event.request, fetchResponse.clone());
return fetchResponse;
}
} catch (error) {
console.log("Fetch failed: ", error);
const cachedResponse = await cache.match("index.html");
return cachedResponse;
}
})()
);
});