From 3fbcde9048e8b502a9b792b12b2cc6d8647adc7a Mon Sep 17 00:00:00 2001 From: Alex Rickabaugh Date: Wed, 29 Nov 2017 13:24:20 -0800 Subject: [PATCH] fix(service-worker): send initialization signal from the application The Service Worker contains a mechanism by which it will postMessage itself a signal to initialize its caches. Through this mechanism, initialization happens asynchronously while keeping the SW process alive. Unfortunately in Firefox, the SW does not have the ability to postMessage itself during the activation event. This prevents the above mechanism from working, and the SW initializes on the next fetch event, which is often too late. Therefore, this change has the application wait for SW changes and tells each new SW to initialize itself. This happens in addition to the self-signal that the SW attempts to send (as self-signaling is more reliable). That way even on browsers such as Firefox, initialization happens eagerly. --- packages/service-worker/src/module.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/packages/service-worker/src/module.ts b/packages/service-worker/src/module.ts index ed5609cf94..297a4faff5 100644 --- a/packages/service-worker/src/module.ts +++ b/packages/service-worker/src/module.ts @@ -35,6 +35,15 @@ export function ngswAppInitializer( const isStable = op_take.call(onStable, 1) as Observable; const whenStable = op_toPromise.call(isStable) as Promise; + // 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'}); + } + }); + // Don't return the Promise, as that will block the application until the SW is registered, and // cause a crash if the SW registration fails. whenStable.then(() => navigator.serviceWorker.register(script, {scope: options.scope}));