-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
81 lines (73 loc) · 2.43 KB
/
sw.js
File metadata and controls
81 lines (73 loc) · 2.43 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
const CACHE_NAME = "mr-core-cache-v3";
const OFFLINE_URL = "/offline.html";
const CORE_ASSETS = [
OFFLINE_URL,
"/manifest.webmanifest",
"/src/CoreSans-Regular_en.otf",
"/src/mrc-nuca.svg",
];
self.addEventListener("install", (event) => {
self.skipWaiting();
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
console.log("[SW] Precaching Core Assets");
return cache.addAll(CORE_ASSETS);
}),
);
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches
.keys()
.then((cacheNames) => {
return Promise.all(
cacheNames.map((cache) => {
if (cache !== CACHE_NAME) {
console.log("[SW] Clearing old cache:", cache);
return caches.delete(cache);
}
}),
);
})
.then(() => self.clients.claim()),
);
});
self.addEventListener("fetch", (event) => {
const request = event.request;
if (request.method !== "GET") return;
if (
request.mode === "navigate" ||
request.headers.get("accept").includes("text/html")
) {
event.respondWith(
fetch(request)
.then((response) => {
const clone = response.clone();
caches.open(CACHE_NAME).then((cache) => cache.put(request, clone));
return response;
})
.catch(async () => {
const cachedResponse = await caches.match(request);
if (cachedResponse) return cachedResponse;
return caches.match(OFFLINE_URL);
}),
);
return;
}
if (["font", "image", "style", "script"].includes(request.destination)) {
event.respondWith(
caches.match(request).then((cachedResponse) => {
const fetchPromise = fetch(request)
.then((networkResponse) => {
caches.open(CACHE_NAME).then((cache) => {
cache.put(request, networkResponse.clone());
});
return networkResponse;
})
.catch(() => null);
return cachedResponse || fetchPromise;
}),
);
return;
}
});