Skip to content

Commit 4cfba58

Browse files
JiaLiPassionAndrewKushnir
authored andcommittedApr 25, 2019
feat(service-worker): allow configuring when the SW is registered (#21842)
Fixes #20970 PR Close #21842
1 parent aa53d6c commit 4cfba58

File tree

4 files changed

+58
-16
lines changed

4 files changed

+58
-16
lines changed
 

‎aio/content/guide/service-worker-config.md

+12
Original file line numberDiff line numberDiff line change
@@ -218,3 +218,15 @@ If the field is omitted, it defaults to:
218218
'!/**/*__*/**', // Exclude URLs containing `__` in any other segment.
219219
]
220220
```
221+
222+
## `register options`
223+
224+
<code-example path="service-worker-getting-started/src/app/app.module.ts" linenums="false" header="src/app/app.module.ts" region="sw-module"> </code-example>
225+
You can pass some options to the `register()` method.
226+
- enabled: optional parameter, by default is true, if enabled is false, the module will behave like the browser not support service worker, and service worker will not be registered.
227+
- scope: optional parameter, to specify the subset of your content that you want the service worker to control.
228+
- registrationStrategy: optional parameter, specify a strategy that determines when to register the service worker, the available options are:
229+
- registerWhenStable: this is the default behavior, the service worker will register when the application is stable (no microTasks or macroTasks remain).
230+
- registerImmediately: register immediately without waiting the application to become stable.
231+
- registerDelay:timeout : register after the timeout period, `timeout` is the number of milliseconds to delay registration. For example `registerDelay:5000` would register the service worker after 5 seconds. If the number of `timeout` is not given (`registerDelay`), by default, `timeout` will be `0`, but it is not equal to `registerImmediately`, it will still run a `setTimeout(register, 0)` to wait all `microTasks` to finish then perform registration of the service worker.
232+
- A factory to get Observable : you can also specify a factory which returns an Observable, the service worker will be registered the first time that a value is emitted by the Observable.

‎aio/content/guide/service-worker-getting-started.md

+15-15
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# Getting started with service workers
22

33

4-
This document explains how to enable Angular service worker support in projects that you created with the [Angular CLI](cli). It then uses a simple example to show you a service worker in action, demonstrating loading and basic caching.
4+
This document explains how to enable Angular service worker support in projects that you created with the [Angular CLI](cli). It then uses a simple example to show you a service worker in action, demonstrating loading and basic caching.
55

66
#### Prerequisites
77

@@ -10,26 +10,26 @@ A basic understanding of the information in [Introduction to Angular service wor
1010

1111
## Adding a service worker to your project
1212

13-
To set up the Angular service worker in your project, use the CLI command `ng add @angular/pwa`. It takes care of configuring your app to use service workers by adding the `service-worker` package along
13+
To set up the Angular service worker in your project, use the CLI command `ng add @angular/pwa`. It takes care of configuring your app to use service workers by adding the `service-worker` package along
1414
with setting up the necessary support files.
1515

1616
```sh
17-
ng add @angular/pwa --project *project-name*
17+
ng add @angular/pwa --project *project-name*
1818
```
1919

2020
The above command completes the following actions:
2121

22-
1. Adds the `@angular/service-worker` package to your project.
22+
1. Adds the `@angular/service-worker` package to your project.
2323
2. Enables service worker build support in the CLI.
2424
3. Imports and registers the service worker in the app module.
2525
4. Updates the `index.html` file:
2626
* Includes a link to add the `manifest.json` file.
2727
* Adds meta tags for `theme-color`.
2828
5. Installs icon files to support the installed Progressive Web App (PWA).
29-
6. Creates the service worker configuration file called [`ngsw-config.json`](/guide/service-worker-config), which specifies the caching behaviors and other settings.
29+
6. Creates the service worker configuration file called [`ngsw-config.json`](/guide/service-worker-config), which specifies the caching behaviors and other settings.
3030

3131

32-
Now, build the project:
32+
Now, build the project:
3333

3434
```sh
3535
ng build --prod
@@ -40,8 +40,8 @@ The CLI project is now set up to use the Angular service worker.
4040

4141
## Service worker in action: a tour
4242

43-
This section demonstrates a service worker in action,
44-
using an example application.
43+
This section demonstrates a service worker in action,
44+
using an example application.
4545

4646
### Serving with `http-server`
4747

@@ -61,7 +61,7 @@ With the server running, you can point your browser at http://localhost:8080/. Y
6161

6262
### Simulating a network issue
6363

64-
To simulate a network issue, disable network interaction for your application. In Chrome:
64+
To simulate a network issue, disable network interaction for your application. In Chrome:
6565

6666
1. Select **Tools** > **Developer Tools** (from the Chrome menu located at the top right corner).
6767
2. Go to the **Network tab**.
@@ -73,9 +73,9 @@ To simulate a network issue, disable network interaction for your application. I
7373

7474
Now the app has no access to network interaction.
7575

76-
For applications that do not use the Angular service worker, refreshing now would display Chrome's Internet disconnected page that says "There is no Internet connection".
76+
For applications that do not use the Angular service worker, refreshing now would display Chrome's Internet disconnected page that says "There is no Internet connection".
7777

78-
With the addition of an Angular service worker, the application behavior changes. On a refresh, the page loads normally.
78+
With the addition of an Angular service worker, the application behavior changes. On a refresh, the page loads normally.
7979

8080
If you look at the Network tab, you can verify that the service worker is active.
8181

@@ -107,12 +107,12 @@ Pay attention to two key points:
107107

108108
### Making changes to your application
109109

110-
Now that you've seen how service workers cache your application, the
111-
next step is understanding how updates work.
110+
Now that you've seen how service workers cache your application, the
111+
next step is understanding how updates work.
112112

113113
1. If you're testing in an incognito window, open a second blank tab. This will keep the incognito and the cache state alive during your test.
114114

115-
2. Close the application tab, but not the window. This should also close the Developer Tools.
115+
2. Close the application tab, but not the window. This should also close the Developer Tools.
116116

117117
3. Shut down `http-server`.
118118

@@ -156,4 +156,4 @@ The service worker installed the updated version of your app *in the background*
156156
## More on Angular service workers
157157

158158
You may also be interested in the following:
159-
* [Communicating with service workers](guide/service-worker-communications).
159+
* [Communicating with service workers](guide/service-worker-communications).

‎packages/service-worker/src/module.ts

+30-1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
import {isPlatformBrowser} from '@angular/common';
1010
import {APP_INITIALIZER, ApplicationRef, InjectionToken, Injector, ModuleWithProviders, NgModule, PLATFORM_ID} from '@angular/core';
11+
import {Observable} from 'rxjs';
1112
import {filter, take} from 'rxjs/operators';
1213

1314
import {NgswCommChannel} from './low_level';
@@ -41,6 +42,8 @@ export abstract class SwRegistrationOptions {
4142
* [ServiceWorkerContainer#register()](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).
4243
*/
4344
scope?: string;
45+
46+
registrationStrategy?: (() => Observable<any>)|string;
4447
}
4548

4649
export const SCRIPT = new InjectionToken<string>('NGSW_REGISTER_SCRIPT');
@@ -68,7 +71,33 @@ export function ngswAppInitializer(
6871

6972
// Don't return the Promise, as that will block the application until the SW is registered, and
7073
// cause a crash if the SW registration fails.
71-
whenStable.then(() => navigator.serviceWorker.register(script, {scope: options.scope}));
74+
if (typeof options.registrationStrategy === 'function') {
75+
const observable = options.registrationStrategy();
76+
const subscription = observable.subscribe(() => {
77+
navigator.serviceWorker.register(script, {scope: options.scope});
78+
subscription.unsubscribe();
79+
});
80+
} else {
81+
const registrationStrategy = typeof options.registrationStrategy === 'string' ?
82+
options.registrationStrategy :
83+
'registerWhenStable';
84+
if (registrationStrategy === 'registerWhenStable') {
85+
whenStable.then(() => navigator.serviceWorker.register(script, {scope: options.scope}));
86+
} else if (registrationStrategy === 'registerImmediately') {
87+
navigator.serviceWorker.register(script, {scope: options.scope});
88+
} else if (registrationStrategy.indexOf('registerDelay') !== -1) {
89+
const split = registrationStrategy.split(':');
90+
const delayStr = split.length > 1 ? split[1] : undefined;
91+
const delay = Number(delayStr);
92+
setTimeout(
93+
() => navigator.serviceWorker.register(script, {scope: options.scope}),
94+
typeof delay === 'number' ? delay : 0);
95+
} else {
96+
// wrong strategy
97+
throw new Error(
98+
`Unknown service worker registration strategy: ${options.registrationStrategy}`);
99+
}
100+
}
72101
};
73102
return initializer;
74103
}

‎tools/public_api_guard/service-worker/service-worker.d.ts

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ export declare class SwPush {
2121

2222
export declare abstract class SwRegistrationOptions {
2323
enabled?: boolean;
24+
registrationStrategy?: (() => Observable<any>) | string;
2425
scope?: string;
2526
}
2627

0 commit comments

Comments
 (0)