Skip to content

Commit

Permalink
fix(service-worker): remove controllerchange listener when app is d…
Browse files Browse the repository at this point in the history
…estroyed

This commit updates the `ngswAppInitializer` implementation and removes the `controllerchange`
listener upon the destruction of the `ApplicationRef`. This adjustment aims to prevent memory
leaks. In a zone.js environment, neglecting to do so could lead to the perpetual creation of
a zone task, which captures the zone and obstructs proper garbage collection.
  • Loading branch information
arturovt committed May 22, 2024
1 parent faf922b commit 5eca4b5
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions packages/service-worker/src/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,18 @@ export function ngswAppInitializer(
return;
}

const appRef = injector.get(ApplicationRef);

// Wait for service worker controller changes, and fire an INITIALIZE action when a new SW
// becomes active. This allows the SW to initialize itself even if there is no application
// traffic.
navigator.serviceWorker.addEventListener('controllerchange', () => {
if (navigator.serviceWorker.controller !== null) {
navigator.serviceWorker.controller.postMessage({action: 'INITIALIZE'});
}
const sw = navigator.serviceWorker;
const onControllerChange = () => sw.controller?.postMessage({action: 'INITIALIZE'});

sw.addEventListener('controllerchange', onControllerChange);

appRef.onDestroy(() => {
sw.removeEventListener('controllerchange', onControllerChange);
});

let readyToRegister$: Observable<unknown>;
Expand Down

0 comments on commit 5eca4b5

Please sign in to comment.