🐛 Reload the page when a new service worker takes over

The worker is registered with autoUpdate and claims its clients, so
after a deploy the new worker took the page over while the old page
kept running with its lazy route chunks purged from the cache:
navigating then failed until the user reloaded by hand.

Once a worker controls the page, a controllerchange now reloads it,
one time per load. The check that a controller already exists keeps
the first visit from reloading, where the brand new worker claims the
page right after registering. The block runs in production only, so
tests never touch it.
This commit is contained in:
2026-12-01 19:10:49 +01:00
parent 49538e8ae3
commit 4359bedde4
+4 -1
View File
@@ -38,7 +38,10 @@
onMount(() => {
void resolveGate().then((g) => (gate = g));
if (import.meta.env.PROD && 'serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js', { scope: '/' }).catch(() => {});
const sw = navigator.serviceWorker;
// A new worker takes the page over once it is active; its lazy route chunks are gone by then, so load the page anew.
if (sw.controller) sw.addEventListener('controllerchange', () => location.reload(), { once: true });
void sw.register('/sw.js', { scope: '/' }).catch(() => {});
}
const tickInterval = setInterval(() => tick++, 15_000);
return () => clearInterval(tickInterval);