DEV Community

Harshal Shah
Harshal Shah

Posted on • Originally published at blogpedia.org

Turn your angular application into PWA through service worker

What is Service worker?

A Service worker is a script (JavaScript file) that runs in background and contributes in offline first web application development. A Service worker cannot directly interact with the webpage nor it can directly access the DOM. It runs on a different thread but can communicate with webpages through messages (Post Messages).

Service workers are fully asynchronous. They are working on a different thread that’s why they don’t block your application in any way.

APIs such as synchronous XHR and localStorage can’t be used inside a service worker.

Service workers are terminated when not in use and restored when required.

Service workers function as a network proxy. They intercept all outgoing HTTP requests made by the application and can choose how to respond to them. For example, they can query a local cache and deliver a cached response if one is available. Proxying isn't limited to requests made through programmatic APIs, such as fetch; it also includes resources referenced in HTML and even the initial request to index.html. Service worker-based caching is thus completely programmable and doesn't rely on server-specified caching headers.

Service Workers in Angular

Starting with version 5.0.0, Angular ships with a service worker implementation. Angular developers can take advantage of this service worker and benefit from the increased reliability and performance it provides, without needing to code against low-level APIs.

The Angular service worker's behavior follows that design goal:

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 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.

Why to add Service Worker in Angular application?

Simple answer of this question is, to convert your application to WPA (Web Progressive Application) which responds even when there is no network connection.

How to add Service Worker?

Adding Service workers in angular app is as easy as adding a module. You just need to run following command.

ng add @angular/pwa --project project-name

where project-name Is a name you already defined in your angular.json file.

The above command will do following code change in your angular project out of the box. You do not need to do anything.

1.Enables service worker build support in the CLI by installing related packages (‘@angular/pwa’ and ‘@angular/service-worker’). It also add those package in package.json file.

  1. Add following lines in index.html
  1. Add following line in app.module imports.

ServiceWorkerModule.register('ngsw-worker.js', { enabled: true })

  1. Create manifes.webmanifest file is src folder

  2. Create service worker configuration file called ngsw-config.json file in root folder

  3. Update angular.json file with following changes in configuration object.

"configuration": {

"production": {

    "serviceWorker": true,

     "ngswConfigPath": "ngsw-config.json"

}

}

  1. Installs icon files to support the installed Progressive Web App (PWA).

How to debug Service Worker?

1.Build the project
ng build –prod

  1. Run the project with http-server
    http-server –port 8080 dist

  2. Go to localhost:8080 in browser. When you load first time with network, it will cached necessary resources(whatever you have mentioned in config file).

  3. Go to network , checked offline and make network unavailable. Refresh the page and observe the network tab. You will see little gear icon and in the initiator column, you will see initiated by service-worker.js file.

Another way to debug whether Service workers are working correctly or not:

To see the audits results, go to Audits in the developer tools of Google Chrome and run the audits. Audits will tell you whether your application satisfies all the criteria for PWA or not. If service workers are working correctly then you will see green dot next to following points:

  • Registers a service worker that controls page and start_url
  • Current page responds with a 200 when offline
  • start_url responds with a 200 when offline

Above three points are the proof that your service workers are working correctly.

See how easy to convert your angular application to PWA. Convert it today and let me know the feedback in comment.

Top comments (0)