Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions adev-es/src/app/routing/sub-navigation-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -915,7 +915,7 @@ const DOCS_SUB_NAVIGATION_DATA: NavigationItem[] = [
],
},
{
label: 'Extended Ecosystem',
label: 'Ecosistema extendido',
children: [
{
label: 'NgModules',
Expand Down Expand Up @@ -976,42 +976,42 @@ const DOCS_SUB_NAVIGATION_DATA: NavigationItem[] = [
label: 'Service Workers & PWAs',
children: [
{
label: 'Overview',
label: 'Visión general',
path: 'ecosystem/service-workers',
contentPath: 'ecosystem/service-workers/overview',
},
{
label: 'Getting started',
label: 'Empezando',
path: 'ecosystem/service-workers/getting-started',
contentPath: 'ecosystem/service-workers/getting-started',
},
{
label: 'Custom service worker scripts',
label: 'Scripts de service worker personalizados',
path: 'ecosystem/service-workers/custom-service-worker-scripts',
contentPath: 'ecosystem/service-workers/custom-service-worker-scripts',
},
{
label: 'Configuration file',
label: 'Archivo de configuración',
path: 'ecosystem/service-workers/config',
contentPath: 'ecosystem/service-workers/config',
},
{
label: 'Communicating with the service worker',
label: 'Comunicación con el service worker',
path: 'ecosystem/service-workers/communications',
contentPath: 'ecosystem/service-workers/communications',
},
{
label: 'Push notifications',
label: 'Notificaciones push',
path: 'ecosystem/service-workers/push-notifications',
contentPath: 'ecosystem/service-workers/push-notifications',
},
{
label: 'Service worker devops',
label: 'Devops del service worker',
path: 'ecosystem/service-workers/devops',
contentPath: 'ecosystem/service-workers/devops',
},
{
label: 'App shell pattern',
label: 'Patrón App shell',
path: 'ecosystem/service-workers/app-shell',
contentPath: 'ecosystem/service-workers/app-shell',
},
Expand Down
64 changes: 64 additions & 0 deletions adev-es/src/content/ecosystem/service-workers/app-shell.en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# App shell pattern

The [App shell pattern](https://developer.chrome.com/blog/app-shell) is a way to render a portion of your application using a route at build time.
It can improve the user experience by quickly launching a static rendered page (a skeleton common to all pages) while the browser downloads the full client version and switches to it automatically after the code loads.

This gives users a meaningful first paint of your application that appears quickly because the browser can render the HTML and CSS without the need to initialize any JavaScript.

<docs-workflow>
<docs-step title="Prepare the application">
Do this with the following Angular CLI command:

<docs-code language="shell">

ng new my-app

</docs-code>

For an existing application, you have to manually add the `Router` and defining a `<router-outlet>` within your application.
</docs-step>
<docs-step title="Create the application shell">
Use the Angular CLI to automatically create the application shell.

<docs-code language="shell">

ng generate app-shell

</docs-code>

For more information about this command, see [App shell command](cli/generate/app-shell).

The command updates the application code and adds extra files to the project structure.

<docs-code language="text">
src
├── app
│ ├── app.config.server.ts # server application configuration
│ └── app-shell # app-shell component
│ ├── app-shell.component.html
│ ├── app-shell.component.scss
│ ├── app-shell.component.spec.ts
│ └── app-shell.component.ts
└── main.server.ts # main server application bootstrapping
</docs-code>

<docs-step title="Verify the application is built with the shell content">

<docs-code language="shell">

ng build --configuration=development

</docs-code>

Or to use the production configuration.

<docs-code language="shell">

ng build

</docs-code>

To verify the build output, open <code class="no-auto-link">dist/my-app/browser/index.html</code>.
Look for default text `app-shell works!` to show that the application shell route was rendered as part of the output.
</docs-step>
</docs-workflow>
36 changes: 18 additions & 18 deletions adev-es/src/content/ecosystem/service-workers/app-shell.md
Original file line number Diff line number Diff line change
@@ -1,64 +1,64 @@
# App shell pattern
# Patrón App shell

The [App shell pattern](https://developer.chrome.com/blog/app-shell) is a way to render a portion of your application using a route at build time.
It can improve the user experience by quickly launching a static rendered page (a skeleton common to all pages) while the browser downloads the full client version and switches to it automatically after the code loads.
El [patrón App shell](https://developer.chrome.com/blog/app-shell) es una forma de renderizar una parte de tu aplicación usando una ruta en tiempo de compilación.
Puede mejorar la experiencia de usuario al lanzar rápidamente una página estática renderizada (un esqueleto común a todas las páginas) mientras el navegador descarga la versión completa del cliente y cambia a ella automáticamente cuando el código termina de cargar.

This gives users a meaningful first paint of your application that appears quickly because the browser can render the HTML and CSS without the need to initialize any JavaScript.
Esto brinda a las personas usuarias un primer render significativo de tu aplicación que aparece rápidamente porque el navegador puede mostrar el HTML y el CSS sin necesidad de inicializar JavaScript.

<docs-workflow>
<docs-step title="Prepare the application">
Do this with the following Angular CLI command:
<docs-step title="Preparar la aplicación">
Hazlo con el siguiente comando de Angular CLI:

<docs-code language="shell">

ng new my-app

</docs-code>

For an existing application, you have to manually add the `Router` and defining a `<router-outlet>` within your application.
Para una aplicación existente, debes agregar manualmente el `Router` y definir un `<router-outlet>` dentro de tu aplicación.
</docs-step>
<docs-step title="Create the application shell">
Use the Angular CLI to automatically create the application shell.
<docs-step title="Crear el shell de la aplicación">
Usa Angular CLI para crear automáticamente el shell de la aplicación.

<docs-code language="shell">

ng generate app-shell

</docs-code>

For more information about this command, see [App shell command](cli/generate/app-shell).
Para obtener más información sobre este comando, consulta [App shell command](cli/generate/app-shell).

The command updates the application code and adds extra files to the project structure.
El comando actualiza el código de la aplicación y agrega archivos adicionales a la estructura del proyecto.

<docs-code language="text">
src
├── app
│ ├── app.config.server.ts # server application configuration
│ └── app-shell # app-shell component
│ ├── app.config.server.ts # configuración de la aplicación del servidor
│ └── app-shell # componente app-shell
│ ├── app-shell.component.html
│ ├── app-shell.component.scss
│ ├── app-shell.component.spec.ts
│ └── app-shell.component.ts
└── main.server.ts # main server application bootstrapping
└── main.server.ts # arranque principal de la aplicación del servidor
</docs-code>

<docs-step title="Verify the application is built with the shell content">
<docs-step title="Verificar que la aplicación se construye con el contenido del shell">

<docs-code language="shell">

ng build --configuration=development

</docs-code>

Or to use the production configuration.
O usa la configuración de producción.

<docs-code language="shell">

ng build

</docs-code>

To verify the build output, open <code class="no-auto-link">dist/my-app/browser/index.html</code>.
Look for default text `app-shell works!` to show that the application shell route was rendered as part of the output.
Para verificar el resultado de la compilación, abre <code class="no-auto-link">dist/my-app/browser/index.html</code>.
Busca el texto predeterminado `app-shell works!` para confirmar que la ruta del shell de la aplicación se renderizó como parte de la salida.
</docs-step>
</docs-workflow>
108 changes: 108 additions & 0 deletions adev-es/src/content/ecosystem/service-workers/communications.en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# Communicating with the Service Worker

Enabling service worker support does more than just register the service worker; it also provides services you can use to interact with the service worker and control the caching of your application.

## `SwUpdate` service

The `SwUpdate` service gives you access to events that indicate when the service worker discovers and installs an available update for your application.

The `SwUpdate` service supports three separate operations:

* Receiving notifications when an updated version is *detected* on the server, *installed and ready* to be used locally or when an *installation fails*.
* Asking the service worker to check the server for new updates.
* Asking the service worker to activate the latest version of the application for the current tab.

### Version updates

The `versionUpdates` is an `Observable` property of `SwUpdate` and emits five event types:

| Event types | Details |
|:--- |:--- |
| `VersionDetectedEvent` | Emitted when the service worker has detected a new version of the app on the server and is about to start downloading it. |
| `NoNewVersionDetectedEvent` | Emitted when the service worker has checked the version of the app on the server and did not find a new version. |
| `VersionReadyEvent` | Emitted when a new version of the app is available to be activated by clients. It may be used to notify the user of an available update or prompt them to refresh the page. |
| `VersionInstallationFailedEvent` | Emitted when the installation of a new version failed. It may be used for logging/monitoring purposes. |
| `VersionFailedEvent` | Emitted when a version encounters a critical failure (such as broken hash errors) that affects all clients using that version. Provides error details for debugging and transparency. |

<docs-code header="log-update.service.ts" path="adev/src/content/examples/service-worker-getting-started/src/app/log-update.service.ts" visibleRegion="sw-update"/>

### Checking for updates

It's possible to ask the service worker to check if any updates have been deployed to the server.
The service worker checks for updates during initialization and on each navigation request —that is, when the user navigates from a different address to your application.
However, you might choose to manually check for updates if you have a site that changes frequently or want updates to happen on a schedule.

Do this with the `checkForUpdate()` method:

<docs-code header="check-for-update.service.ts" path="adev/src/content/examples/service-worker-getting-started/src/app/check-for-update.service.ts"/>

This method returns a `Promise<boolean>` which indicates if an update is available for activation.
The check might fail, which will cause a rejection of the `Promise`.

<docs-callout important title="Stabilization and service worker registration">
In order to avoid negatively affecting the initial rendering of the page, by default the Angular service worker service waits for up to 30 seconds for the application to stabilize before registering the ServiceWorker script.

Constantly polling for updates, for example, with [setInterval()](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) or RxJS' [interval()](https://rxjs.dev/api/index/function/interval), prevents the application from stabilizing and the ServiceWorker script is not registered with the browser until the 30 seconds upper limit is reached.

This is true for any kind of polling done by your application.
Check the [isStable](api/core/ApplicationRef#isStable) documentation for more information.

Avoid that delay by waiting for the application to stabilize first, before starting to poll for updates, as shown in the preceding example.
Alternatively, you might want to define a different [registration strategy](api/service-worker/SwRegistrationOptions#registrationStrategy) for the ServiceWorker.
</docs-callout>

### Updating to the latest version

You can update an existing tab to the latest version by reloading the page as soon as a new version is ready.
To avoid disrupting the user's progress, it is generally a good idea to prompt the user and let them confirm that it is OK to reload the page and update to the latest version:

<docs-code header="prompt-update.service.ts" path="adev/src/content/examples/service-worker-getting-started/src/app/prompt-update.service.ts" visibleRegion="sw-version-ready"/>

<docs-callout important title="Safety of updating without reloading">
Calling `activateUpdate()` updates a tab to the latest version without reloading the page, but this could break the application.

Updating without reloading can create a version mismatch between the application shell and other page resources, such as lazy-loaded chunks, whose filenames may change between versions.

You should only use `activateUpdate()`, if you are certain it is safe for your specific use case.
</docs-callout>

### Handling an unrecoverable state

In some cases, the version of the application used by the service worker to serve a client might be in a broken state that cannot be recovered from without a full page reload.

For example, imagine the following scenario:

1. A user opens the application for the first time and the service worker caches the latest version of the application.
Assume the application's cached assets include `index.html`, `main.<main-hash-1>.js` and `lazy-chunk.<lazy-hash-1>.js`.

1. The user closes the application and does not open it for a while.
1. After some time, a new version of the application is deployed to the server.
This newer version includes the files `index.html`, `main.<main-hash-2>.js` and `lazy-chunk.<lazy-hash-2>.js`.

IMPORTANT: The hashes are different now, because the content of the files changed. The old version is no longer available on the server.

1. In the meantime, the user's browser decides to evict `lazy-chunk.<lazy-hash-1>.js` from its cache.
Browsers might decide to evict specific (or all) resources from a cache in order to reclaim disk space.

1. The user opens the application again.
The service worker serves the latest version known to it at this point, namely the old version (`index.html` and `main.<main-hash-1>.js`).

1. At some later point, the application requests the lazy bundle, `lazy-chunk.<lazy-hash-1>.js`.
1. The service worker is unable to find the asset in the cache (remember that the browser evicted it).
Nor is it able to retrieve it from the server (because the server now only has `lazy-chunk.<lazy-hash-2>.js` from the newer version).

In the preceding scenario, the service worker is not able to serve an asset that would normally be cached.
That particular application version is broken and there is no way to fix the state of the client without reloading the page.
In such cases, the service worker notifies the client by sending an `UnrecoverableStateEvent` event.
Subscribe to `SwUpdate#unrecoverable` to be notified and handle these errors.

<docs-code header="handle-unrecoverable-state.service.ts" path="adev/src/content/examples/service-worker-getting-started/src/app/handle-unrecoverable-state.service.ts" visibleRegion="sw-unrecoverable-state"/>

## More on Angular service workers

You might also be interested in the following:

<docs-pill-row>
<docs-pill href="ecosystem/service-workers/push-notifications" title="Push notifications"/>
<docs-pill href="ecosystem/service-workers/devops" title="Service Worker devops"/>
</docs-pill-row>
Loading