-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice-worker.js
52 lines (44 loc) · 1.66 KB
/
service-worker.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
const CACHE_NAME = 'index'
const OFFLINE_URL = 'index.html'
self.addEventListener('install', function (event) {
console.log('[ServiceWorker] Install')
event.waitUntil((async () => {
const cache = await caches.open(CACHE_NAME)
// Setting {cache: 'reload'} in the new request will ensure that the response
// isn't fulfilled from the HTTP cache; i.e., it will be from the network.
await cache.add(new Request(OFFLINE_URL, { cache: 'reload' }))
})())
self.skipWaiting()
})
self.addEventListener('activate', (event) => {
console.log('[ServiceWorker] Activate')
event.waitUntil((async () => {
// Enable navigation preload if it's supported.
// See https://developers.google.com/web/updates/2017/02/navigation-preload
if ('navigationPreload' in self.registration) {
await self.registration.navigationPreload.enable()
}
})())
// Tell the active service worker to take control of the page immediately.
self.clients.claim()
})
self.addEventListener('fetch', function (event) {
// console.log('[Service Worker] Fetch', event.request.url);
if (event.request.mode === 'navigate') {
event.respondWith((async () => {
try {
const preloadResponse = await event.preloadResponse
if (preloadResponse) {
return preloadResponse
}
const networkResponse = await fetch(event.request)
return networkResponse
} catch (error) {
console.log('[Service Worker] Fetch failed; returning offline page instead.', error)
const cache = await caches.open(CACHE_NAME)
const cachedResponse = await cache.match(OFFLINE_URL)
return cachedResponse
}
})())
}
})