Skip to main content

Angular Service Worker

Adding a service worker to an Angular application is one of the steps for turning an application into a Progressive Web App (also known as a PWA).

Angular's service worker is designed to optimize the end user experience of using an application over a slow or unreliable network connection, while also minimizing the risks of serving outdated content.

To achieve this, the Angular service worker follows these guidelines:

  • Caching an application is like installing a native application. The application is cached as one unit, and all files update together.
  • A running application continues to run with the same version of all files. It does not suddenly start receiving cached files from a newer version, which are likely incompatible.
  • When users refresh the application, they see the latest fully cached version. New tabs load the latest cached code.
  • Updates happen in the background, relatively quickly after changes are published. The previous version of the application is served until an update is installed and ready.
  • The service worker conserves bandwidth when possible. Resources are only downloaded if they've changed.

To support these behaviors, the Angular service worker loads a manifest file from the server. The file, called ngsw.json (not to be confused with the web app manifest), describes the resources to cache and includes hashes of every file's contents. When an update to the application is deployed, the contents of the manifest change, informing the service worker that a new version of the application should be downloaded and cached. This manifest is generated from a CLI-generated configuration file called ngsw-config.json.

Service worker communication

Importing ServiceWorkerModule into your AppModule doesn't just register the service worker, it also provides a few services you can use to interact with the service worker and control the caching of your application.