-
Notifications
You must be signed in to change notification settings - Fork 34
/
service-worker-registration.ts
54 lines (40 loc) · 1.38 KB
/
service-worker-registration.ts
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
/* eslint-disable no-console */
import extractInlineScripts from './extract-inline-scripts'
const REVALIDATION_INTERVAL_HOURS = 1
const register = () => {
window.addEventListener(
'load',
async () => {
try {
const registration = await navigator.serviceWorker.register('/service-worker.js')
console.log('Service worker registered!')
registration.addEventListener('updatefound', () => {
registration.installing?.postMessage({ inlineAssets: extractInlineScripts() })
})
setInterval(() => registration.update(), REVALIDATION_INTERVAL_HOURS * 3600 * 1000)
} catch (err) {
console.error(err)
}
},
{ once: true }
)
navigator.serviceWorker?.addEventListener('message', async event => {
const { navigationPreloadHeader } = event.data
const registration = await navigator.serviceWorker.ready
registration.navigationPreload.setHeaderValue(navigationPreloadHeader)
})
}
const unregister = async () => {
try {
const registration = await navigator.serviceWorker.ready
await registration.unregister()
console.log('Service worker unregistered!')
} catch (err) {
console.error(err)
}
}
if ('serviceWorker' in navigator) {
const shouldRegister = process.env.NODE_ENV !== 'development' && navigator.userAgent !== 'Prerender'
if (shouldRegister) register()
else unregister()
}