-
Notifications
You must be signed in to change notification settings - Fork 9
/
sw.js
103 lines (91 loc) · 2.55 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
91
92
93
94
95
96
97
98
99
100
101
102
103
importScripts(
'js/vendor/sw-cacheable-response.min.js',
'js/vendor/sw-routing.min.js',
'js/vendor/sw-runtime-caching.min.js',
'js/vendor/sw-precaching.min.js'
);
// Make this always match package.json version
const version = '0.1.3';
const cacheName = `defaultCache_${version}`;
const { cacheableResponse, precaching, routing, runtimeCaching } = goog;
const router = new routing.Router();
const localhost = registration.scope;
const staticCache = new precaching.UnrevisionedCacheManager({ cacheName });
const requestWrapper = new runtimeCaching.RequestWrapper({ cacheName });
const cdnRequestWrapper = new runtimeCaching.RequestWrapper({
plugins: [
new cacheableResponse.CacheableResponsePlugin({ statuses: [0, 200] })
],
cacheName
});
/**
* Route for local CSS and JS assets
*
* Strategy:
* https://developers.google.com/web/fundamentals/instant-and-offline/
* offline-cookbook/#stale-while-revalidate
*/
const assetRoute = new routing.RegExpRoute({
regExp: new RegExp(`^${localhost}.*\\.(css|js|png|svg)$`),
handler: new runtimeCaching.StaleWhileRevalidate({ requestWrapper })
});
/**
* Route for assets on cloudfront.net CDN
*
* Strategy:
* https://developers.google.com/web/fundamentals/instant-and-offline/
* offline-cookbook/#stale-while-revalidate
*/
const cdnAssetRoute = new routing.RegExpRoute({
regExp: new RegExp('^https://.*\\.cloudfront\\.net/.*\\.(png|svg)$'),
handler: new runtimeCaching.StaleWhileRevalidate({
requestWrapper: cdnRequestWrapper
})
});
/**
* Route for pages
*
* Strategy:
* https://developers.google.com/web/fundamentals/instant-and-offline/
* offline-cookbook/#network-falling-back-to-cache
*/
const navRoute = new routing.NavigationRoute({
whitelist: [/./],
handler: new runtimeCaching.NetworkFirst({ requestWrapper })
});
/**
* Precache resources
*/
staticCache.addToCacheList({
unrevisionedFiles: ['/', '/404/', '/error/']
});
self.oninstall = event => {
event.waitUntil(Promise.all([staticCache.install().then(skipWaiting)]));
};
self.onactivate = event => {
caches.keys().then(keys => {
keys.forEach(cacheName => {
if (!cacheName.endsWith(version)) {
caches.delete(cacheName);
}
});
});
return event.waitUntil(clients.claim());
};
router.registerRoutes({
routes: [assetRoute, cdnAssetRoute, navRoute]
});
/**
* Fallback route for stuff that doesn't match
*/
router.setDefaultHandler({
handler: new runtimeCaching.NetworkOnly()
});
/**
* Catch-all fetch error handler
*/
router.setCatchHandler({
handler: {
handle: () => caches.match('/error/')
}
});