-
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathsw.js
More file actions
94 lines (88 loc) · 2.21 KB
/
sw.js
File metadata and controls
94 lines (88 loc) · 2.21 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
/* eslint-disable import/no-extraneous-dependencies */
import { CacheableResponsePlugin } from "workbox-cacheable-response";
import { cacheNames } from "workbox-core";
import { ExpirationPlugin } from "workbox-expiration";
import {
registerRoute,
setCatchHandler,
setDefaultHandler,
} from "workbox-routing";
import {
NetworkFirst,
NetworkOnly,
StaleWhileRevalidate,
} from "workbox-strategies";
const cacheName = cacheNames.runtime;
const manifest = self.__WB_MANIFEST;
const otherManifest = [
{
url: "/manifest.json",
},
{
url: "/app-shell/index.html",
},
];
const manifestURLs = [
...new Set(
[...manifest, ...otherManifest].map((entry) => {
const url = new URL(entry.url, self.location);
return url.href;
}),
),
];
self.addEventListener("install", (event) => {
event.waitUntil(
(async () => {
const cache = await caches.open(cacheName);
await Promise.allSettled(manifestURLs.map((url) => cache.add(url)));
})(),
);
});
self.addEventListener("activate", (event) => {
// - [x] clean up outdated runtime cache
event.waitUntil(
caches.open(cacheName).then((cache) =>
// clean up those who are not listed in manifestURLs
cache
.keys()
.then((keys) =>
Promise.all(
keys
.filter((request) => !manifestURLs.includes(request.url))
.map((request) => cache.delete(request)),
),
),
),
);
});
registerRoute(
({ url }) => manifestURLs.includes(url.href),
new NetworkFirst({
cacheName,
}),
);
// Cache Google Fonts
registerRoute(
/https:\/\/fonts\.gstatic\.com/,
new StaleWhileRevalidate({
cacheName: "google-fonts-cache",
plugins: [
// Ensure that only requests that result in a 200 status are cached
new CacheableResponsePlugin({
statuses: [200],
}),
new ExpirationPlugin({
// Cache for one year
maxAgeSeconds: 60 * 60 * 24 * 365,
maxEntries: 30,
}),
],
}),
);
setDefaultHandler(new NetworkOnly());
// fallback to app-shell for document request
setCatchHandler(({ event }) => {
if (event.request.destination === "document") {
return caches.match("/app-shell/index.html");
}
});