Tech Insights
Chirath Perera
September 8, 2020

Adding a service worker to an Angular application

Adding a service worker to an Angular application

A service worker is ascript which runs in the background in a browser. It is similar to a proxy. Aproxy works as an interface or a gateway between the user and the internet. Itfacilitates offline tasks. Adding a service worker to any application concernsa PWA (Progressive Web App). PWA is a type of application software that usesmodern web capabilities such as progressiveness, responsiveness, connectivitypendant, app-like features, freshness, safety, discoverability, re-engageability,installability and linkability.

Why do weneed service workers?

A service worker is ascript to manage the caching of an application. It runs in the web browser.Adding a service worker to an Angular application is one of the steps to turnan application into a Progressive Web App. Angular developers can takeadvantage of this service worker and benefit from the increased reliability andperformance it provides, without coding against low-level APIs.
A service worker is used to get push notifications andload data when the application is offline.

When a service workerfile is used, it caches all data which are mentioned in the file. That is thereason why the browser loads old values after deployment.

In creating a serviceworker, what files to be cached can be defined, for e.g.

·        index.html

·        favicon.ico

·        Buildartifacts (JS and CSS bundles)

·        Anythingunder assets

·        Images andfonts etc.

Below is an example ofcontents in service worker JSON file:

view rawngsw.json hosted with❤ by GitHub

Assets are resourcesthat are part of the app version which gets updated along with the app.

The installModedetermines how these resources are initially cached. It can be either of twovalues:

·        prefetch— tells the Angularservice worker to fetch every single listed resource while it’s caching thecurrent version of the app.

·        lazy — does not cache any of the resources up front.

For resources already inthe cache, the updateMode determines the caching behaviour when a new versionof the app is discovered.

·        prefetch— tells the service workerto download and cache the changed resources immediately.

·        lazy — tells the service worker to not cache those resources.

Adding aservice worker to an Angular application - A step-by-step guide

Create a new project

ng new swApp

Add PWA library

ng add @angular/pwa

After this, you can seea couple of new files in your Angular application.

1. Go to src; youcan see a file called manifest.webmanifest. It can be customisedto have any property by changing the relevant values in manifest.webmanifest.This file contains a web application in a JSON text file.

view rawmanifest.webmanifest hosted with ❤ by GitHub

2. ngsw-config.json — ithas files and data URLs the Angular service worker should cache and how itshould update the cached files and data.

view rawngsw-config.json hostedwith ❤ by GitHub

3. app.module.ts

view rawapp.module.ts hostedwith ❤ by GitHub

You can see that theAppModule is trying to register the service worker script in the browser byloading the ngsw-worker.js. This JS file loads in a separate HTTP request byusing register method.

If you test serviceworkers in a test environment with a new instance you should add your instancename as a prefix.

E.g.‘/instanceName/ngsw-worker.js’.

abc-dev.abc.com/sw-test/login

Above URL is an exampleof a test environment. In that, your instance name is sw-test. Therefore youhave to register your service worker in appModule like this -

ServiceWorkerModule.register('/sw-test/ngsw-worker.js',{ enabled: environment.production })

4. After that, run the

ng build --prod

You can see the generated service worker JavaScript files in the file location. (/dist).

5. Before the ng serveyou have to set an HTTP server in your loaclhost, as service workers don’t runin local.

Go to your dist folderand type the below command:

cd dist/your app name-> cd dist/swApp

6. Then type in the cmd

http-server -o

It opens the browser automatically, on the browser, go to inspect-element then select application:

You can see the serviceworker received the time and the service worker file. Browser stores this timeas a timestamp.

Updating the Service Worker

It must be chcked afterevery deployment whether a new version is available. Otherwise the browsermight cache old application versions after reloading. Therefore checking mustbe done for new versions periodically. We can add SwUpdate() method to check anew version after every deployment. Thus, if a new version is available,browser will reload the page automatically. We can add this method in ngOnInitof AppComponent.ts.

app.component.ts

view rawapp.component.ts hostedwith ❤ by GitHub

Summary

Using a service workeris beneficial to load an application faster and manage caching. A serviceworker is a script that runs in the browser background. Adding a service workerto an Angular application is one of the steps to turn the application into aProgressive Web App (PWA). There are technical components of PWA. Those areHTTPS, Manifest.json and Service worker. Therefore, a service worker requiresHTTPS to run in the browser.

Reference

https://angular.io/guide/service-worker-intro

We'll meet again inanother blog post on Angular service workers.