MCPcopy
hub / github.com/angular/angular / ngswAppInitializer

Function ngswAppInitializer

packages/service-worker/src/provider.ts:32–122  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

30);
31
32export function ngswAppInitializer(): void {
33 if (typeof ngServerMode !== 'undefined' && ngServerMode) {
34 return;
35 }
36
37 const options = inject(SwRegistrationOptions);
38
39 if (!('serviceWorker' in navigator && options.enabled !== false)) {
40 return;
41 }
42
43 const script = inject(SCRIPT);
44 const ngZone = inject(NgZone);
45 const appRef = inject(ApplicationRef);
46
47 // Set up the `controllerchange` event listener outside of
48 // the Angular zone to avoid unnecessary change detections,
49 // as this event has no impact on view updates.
50 ngZone.runOutsideAngular(() => {
51 // Wait for service worker controller changes, and fire an INITIALIZE action when a new SW
52 // becomes active. This allows the SW to initialize itself even if there is no application
53 // traffic.
54 const sw = navigator.serviceWorker;
55 const onControllerChange = () => sw.controller?.postMessage({action: 'INITIALIZE'});
56
57 sw.addEventListener('controllerchange', onControllerChange);
58
59 appRef.onDestroy(() => {
60 sw.removeEventListener('controllerchange', onControllerChange);
61 });
62 });
63
64 // Run outside the Angular zone to avoid preventing the app from stabilizing (especially
65 // given that some registration strategies wait for the app to stabilize).
66 ngZone.runOutsideAngular(() => {
67 let readyToRegister: Promise<void>;
68
69 const {registrationStrategy} = options;
70 if (typeof registrationStrategy === 'function') {
71 readyToRegister = new Promise((resolve) => registrationStrategy().subscribe(() => resolve()));
72 } else {
73 const [strategy, ...args] = (registrationStrategy || 'registerWhenStable:30000').split(':');
74
75 switch (strategy) {
76 case 'registerImmediately':
77 readyToRegister = Promise.resolve();
78 break;
79 case 'registerWithDelay':
80 readyToRegister = delayWithTimeout(+args[0] || 0);
81 break;
82 case 'registerWhenStable':
83 readyToRegister = Promise.race([appRef.whenStable(), delayWithTimeout(+args[0])]);
84 break;
85 default:
86 // Unknown strategy.
87 throw new RuntimeError(
88 RuntimeErrorCode.UNKNOWN_REGISTRATION_STRATEGY,
89 (typeof ngDevMode === 'undefined' || ngDevMode) &&

Callers

nothing calls this directly

Calls 15

injectFunction · 0.90
delayWithTimeoutFunction · 0.85
formatRuntimeErrorFunction · 0.85
raceMethod · 0.80
addEventListenerMethod · 0.65
onDestroyMethod · 0.65
removeEventListenerMethod · 0.65
subscribeMethod · 0.65
resolveMethod · 0.65
whenStableMethod · 0.65
thenMethod · 0.65
registerMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…