Service Workers With Angular(Offline Capabilities)

Service Workers With Angular(Offline Capabilities)

Anil Verma's photo
Anil Verma
·Feb 4, 2021·

Subscribe to my newsletter and never miss my upcoming articles

Play this article

The service worker is a script that runs in the web browser and manages caching for an application. It runs on an additional thread and manages all pages/screens of the given scope in the background.

The service worker can catch all outgoing requests and can Cache data and put data in Cache storage. It can return back data while no internet connection.

Steps to Add PWA in Angular

Step -1 run below command

ng add @angular/pwa

Once this command run, it will configure the service worker in your angular project. it will make the following below-mentioned changes in your project-

  1. Will create an icons folder inside your asset folder

2. It will enable service workers in your angular.json file

3. It will add a service worker module in app.module file

4. It will add a manifest file in the src folder and will reference that in index.html

5. It will also create a service worker configuration file in the root with src folder

Step -2 Caching assets

Some caching is already defined in the services worker configuration file under assetGroups arary. initially, its installMode is “prefetch”

installMode -“prefetch” — puts data in cache even it is not needed

installMode -“lazy” — puts data in cache after one time run.

there is one more property updateMode with installMode:”lazy”

updateMode:”prefetch”- It will get informed about new service workers and will prefetch updated data and can install them lazily when they are required.

cache-URLs- in same service worker file in assetGroups add one more entry with “urls” as Array and put your all URLs to be cached here.

Step -3 Caching dynamic data

For Caching dynamic data create a dataGroups Array after assetGroups Array

Name- as per your choice(give any name)

URLs-Put your API URLs in this array

cacheConfig — it will configure, how your datagroup will behave for

“strategy”:string: “freshness” — Always go to the server to get data and only use cached data if offline
“strategy”:string: “performance” — — will load cache data and will go to server based on maxAge

timeout: number- Is server taking longer than 10 seconds than will load cached data

MaxSize: string- How many outgoing requests

After these changes, create a production build and run your application. production build is required because the service worker is set up for production mode(check app.module.ts).

Happy Coding….

 
Share this