Repository navigation
Expand file tree
/
Copy pathServiceWorkerRegister.tsx
More file actions
74 lines (61 loc) · 1.93 KB
/
Copy pathServiceWorkerRegister.tsx
File metadata and controls
74 lines (61 loc) · 1.93 KB
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
'use client';
import { useEffect, useRef } from 'react';
/** Maximum number of retry attempts for service worker registration */
const MAX_SW_RETRIES = 3;
/** Delay in milliseconds between retry attempts (linear backoff) */
const INITIAL_RETRY_DELAY = 1000;
/**
* Registers the service worker on mount, retrying with linear backoff.
*
* Renders nothing. Mount it once, near the root, to give the site its offline support.
*/
export default function ServiceWorkerRegister() {
const retryTimeoutRef = useRef<NodeJS.Timeout | null>(null);
useEffect(() => {
if (!('serviceWorker' in navigator)) {
return;
}
// Set on unmount so a registration still in flight neither logs nor schedules a retry when it settles.
let cancelled = false;
/**
* Register the service worker with linear backoff retry logic
* @param retriesLeft Number of retry attempts remaining
*/
const registerWithRetry = (retriesLeft: number = MAX_SW_RETRIES): void => {
navigator.serviceWorker
.register('/sw.js')
.then((registration) => {
if (cancelled) {
return;
}
console.log('Service Worker registered with scope:', registration.scope);
})
.catch((error) => {
if (cancelled) {
return;
}
if (retriesLeft > 0) {
const delayMs = INITIAL_RETRY_DELAY * (MAX_SW_RETRIES - retriesLeft + 1);
console.warn(
`Service Worker registration failed, retrying in ${delayMs}ms (${retriesLeft} attempts remaining):`,
error,
);
retryTimeoutRef.current = setTimeout(() => {
registerWithRetry(retriesLeft - 1);
}, delayMs);
} else {
console.error('Service Worker registration failed after all retries:', error);
}
});
};
registerWithRetry();
// Cleanup: clear any pending retry timeout on unmount
return () => {
cancelled = true;
if (retryTimeoutRef.current) {
clearTimeout(retryTimeoutRef.current);
}
};
}, []);
return null;
}