-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathservice-worker-registration.js
43 lines (33 loc) · 1.11 KB
/
service-worker-registration.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
/* eslint-disable no-console */
const ACTIVE_REVALIDATION_INTERVAL = 1 * 60 * 60
const PERIODIC_REVALIDATION_INTERVAL = 12 * 60 * 60
const register = () => {
window.addEventListener('load', async () => {
try {
const registration = await navigator.serviceWorker.register('/service-worker.js')
console.log('Service worker registered!')
setInterval(() => registration.update(), ACTIVE_REVALIDATION_INTERVAL * 1000)
const { state } = await navigator.permissions.query({ name: 'periodic-background-sync' })
if (state === 'granted') {
await registration.periodicSync.register('revalidate-assets', {
minInterval: PERIODIC_REVALIDATION_INTERVAL * 1000
})
}
} catch (err) {
console.error(err)
}
})
}
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) {
if (process.env.NODE_ENV === 'development') unregister()
else register()
}