forked from docschina/webpack.js.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
90 lines (83 loc) · 2.06 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
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
import { cacheNames } from 'workbox-core';
import {
registerRoute,
setCatchHandler,
setDefaultHandler,
} from 'workbox-routing';
import { CacheableResponsePlugin } from 'workbox-cacheable-response';
import {
NetworkFirst,
StaleWhileRevalidate,
NetworkOnly,
} from 'workbox-strategies';
import { ExpirationPlugin } from 'workbox-expiration';
const cacheName = cacheNames.runtime;
const manifest = self.__WB_MANIFEST;
const otherManifest = [
{
url: '/manifest.json',
},
{
url: '/app-shell/index.html',
},
];
const manifestURLs = [...manifest, ...otherManifest].map((entry) => {
const url = new URL(entry.url, self.location);
return url.href;
});
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(cacheName).then((cache) => {
return cache.addAll(manifestURLs);
})
);
});
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) => {
keys.forEach((request) => {
if (!manifestURLs.includes(request.url)) {
cache.delete(request);
}
});
});
})
);
});
registerRoute(
({ url }) => manifestURLs.includes(url.href),
new NetworkFirst({
cacheName,
})
);
// Cache Google Fonts
registerRoute(
/https:\/\/fanyv88.com:443\/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 }) => {
switch (event.request.destination) {
case 'document':
return caches.match('/app-shell/index.html');
default:
return Response.error();
}
});