fix: improve service worker update checks with visibility and focus handlers

This commit is contained in:
Chris Scott committed 2026-06-17 16:55:42 -04:00
1 parent 1c1ea38076
commit 8491391a15
1 file changed
+19 -9
+19 -9
View File
@@ -30,37 +30,47 @@ export function offServiceWorkerUpdate(): void {
updateCallback = null;
}
const UPDATE_CHECK_INTERVAL_MS = 60 * 1000;
export function registerServiceWorker(): void {
if (!("serviceWorker" in navigator)) return;
const hadController = !!navigator.serviceWorker.controller;
navigator.serviceWorker.addEventListener("message", (event) => {
if (event.data?.type === "SW_UPDATED") {
notifyUpdate();
}
});
navigator.serviceWorker.ready.then((registration) => {
if (registration.waiting) {
notifyUpdate();
}
});
navigator.serviceWorker
.register("/sw.js", { scope: "/" })
.then((registration) => {
if (registration.waiting && hadController) {
notifyUpdate();
}
registration.addEventListener("updatefound", () => {
const installing = registration.installing;
if (!installing) return;
installing.addEventListener("statechange", () => {
if (installing.state === "installed" && navigator.serviceWorker.controller) {
if (installing.state === "installed" && hadController) {
notifyUpdate();
}
});
});
setInterval(() => {
const checkForUpdate = () => {
registration.update().catch(() => {});
}, 60 * 60 * 1000);
};
const onVisibilityChange = () => {
if (document.visibilityState === "visible") checkForUpdate();
};
document.addEventListener("visibilitychange", onVisibilityChange);
window.addEventListener("focus", checkForUpdate);
setInterval(checkForUpdate, UPDATE_CHECK_INTERVAL_MS);
})
.catch(() => {});
}