Service Worker – Why required and how to implement it in Angular Project?

In this article, we will discuss related how to use the Service Worker in any Angular Applications. From, Angular 5 onwards Angular framework supports the service worker implementation in any project include the support for building the Progressive Web Applications (PWA). Progressive Web Application is also a web-based application that uses the latest web technologies so that the user can feel the application just like an app. So, with the help of PWA, we can remove the gap between the classic web application and a native mobile application. But, in this article, we will not discuss the PWA. We will discuss the concept of Service worker which is essentially required in the case of PWA based application.
 

What is Service Worker in Angular?

 
A service worker is a small JavaScript-based program or rather to say a worker that can run in the background and can intercepts any request, like HTTP requests. It is based on the worker implementation where we can decide what need to do with these requests. Also, using a Service worker, we can implement the caching for the application. So, the service worker function act as a network proxy. It intercepts all outgoing HTTP requests made through the application and then decides how to respond to them. Like, for example, it can query to the local cache and deliver the cached response against any HTTP request if that exists. So, the Service worker-based caching is programmable, and it doesn’t depend on the server-oriented caching layers.
 
As a SPA (Single-Page Application) based application, all the Angular based applications are always the main position to achieve benefits from the advantages of Service workers. A single from Angular 5.0, Angular starts the support the implementation of the service-worker in their application. So, every angular developer can take the benefits of the service workers and also get the advantages due to the increased reliability and performance it provides without writing the code against the low-level APIs.
 
 

Benefits of Service Worker

 
The Service workers in the Angular Framework provides the following design goals or benefits –
  1. We can perform caching an application is just like installing a native application. The entire application is cached as one unit, and all files update together.
  2. The running application can be run with the same version of all the files. It does not suddenly start receiving the cached files from a newer version, which may occur to unstable the application.
  3. When the user refreshes the application, they normally see the latest fully cached version of the application. New tabs of the browser also load the latest cached code.
  4. In the cached application, the new updates always happened in the background when the changes are published. The previous version of the application always served until an update is installed and ready.
  5. The service worker can conserve the bandwidth when possible. Resources are only be downloaded if they have changed in the source.
To implement these behaviors or benefits related to the service worker, the Angular service worker loads a MANIFEST file from the server. The manifest file describes the resources to cache and includes hashes of every file's contents. When an update to the application is deployed in the server, 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.
 
For service workers to be registered in the application, the application must be accessed over HTTPS, not HTTP. Browsers always ignore service workers on pages that are served over an insecure connection or HTTP. The reason is that service workers are quite powerful, so extra care needs to be taken to ensure the service worker script has not been tampered with. To make local development easier, browsers do NOT require a secure connection when accessing an app on localhost. Currently, service workers are supported in the latest versions of Chrome, Firefox, Edge, Safari, Opera, UC Browser (Android version), and Samsung Internet. Browsers like IE and Opera Mini do not support service workers.
 

Life Cycle of Service Worker

 
In any angular application, the service worker always maintains a separate lifecycle compared to the web page. To install or activate the service worker for the application, we need to first register into the browser which can be done by using the script section of our pages. While we register the service worker, it will cause the web browser to start the service worker installation steps in the background. Basically, during these installation steps, we can cache some static assets files related to the CSS, images, JS, etc. the installation process, if all the files are cached successfully, then the service worker becomes installed. If any of the files or assets fail to download and cache, then the installation steps will fail and the service worker would not be installed or activated. In that case, it will try again the next time when the application will be accessed again.
 
So, when the service worker is installed successfully, the entire activation steps will follow and it will provide us a great chance to handling any management of old caches which can be handled during the service worker update section. So, after the activation of the installation steps, the service worker will control all pages which fall under its scope. Once the service worker is in control, it will be in one of two states: either the service worker will be terminated to save memory, or it will handle fetch and message events that occur when a network request or message is made from your page.
 

About Service-Worker Configuration File

 
The Service-worker configuration file is the Angular Service worker itself. Just like other service workers, it gets delivered via its separate HTTP request so that the browser can track if it has changed or updated and can apply it to the Service Worker Lifecycle. Note that the Angular Service worker file ngsw-worker.js will always be the same for each build since it is get copied from the node modules directly. This file will remain unchanged until we do not perform any changes into the Angular version which may contain the new version of the Angular Service Worker.
 
ngsw.json file is the runtime configuration file, which is mainly used by the Angular Service Worker. This file is mainly built based on the ngsw-config.json file and it contains all the information needed by the Angular Service Worker to identify at runtime which files need to be cached and when.
  1. {  
  2.   "$schema""./node_modules/@angular/service-worker/config/schema.json",  
  3.   "index""/index.html",  
  4.   "assetGroups": [  
  5.     {  
  6.       "name""app",  
  7.       "installMode""prefetch",  
  8.       "resources": {  
  9.         "files": [  
  10.           "/favicon.ico",  
  11.           "/index.html",  
  12.           "/manifest.webmanifest",  
  13.           "/*.css",  
  14.           "/*.js"  
  15.         ]  
  16.       }  
  17.     },  
  18.     {  
  19.       "name""assets",  
  20.       "installMode""lazy",  
  21.       "updateMode""prefetch",  
  22.       "resources": {  
  23.         "files": [  
  24.           "/assets/**",  
  25.           "/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"  
  26.         ]  
  27.       }  
  28.     }  
  29.   ]  
  30. }  
 
The Angular Service Worker is going to load these files under the assets group either proactively in the case of install mode prefetch, or as needed in the case of install mode lazy, and it will also store the files in Cache Storage. This loading is going to happen in the background, as the user first loads the application. The next time that the user refreshes the page, then the Angular Service Worker is going to intercept the HTTP requests and will serve the cached files instead of getting them from the network. Note that each asset will have a hash entry in the hash table. If we do any modification to any of the files listed there, we will have a completely different hash in the following Angular CLI build. The Angular Service Worker will then know that this file has a new version available on the server that needs to be loaded at the appropriate time. Now that we have a good overview of everything that is going on, let's see this in action.
 

How to Enable Service Worker

 
To enable or setup the Angular Service worker in any angular application-based project, we need to perform the following steps which take care the configuring our application to use the service workers by including the service-worker package into the application.
 
Step 1 
Add the @angular/service-worker package to our application by using npm install command
 
Step 2
We need to enable the service worker to build support in the CLI.
 
 
 
Step 3 
Imports and register the service worker in the app module.
 
 
 
Step 4 
Create the service worker configuration file called ngsw-config.json which mainly specify all caching behaviors and other setting related to the service worker.
  1. {  
  2.   "$schema""./node_modules/@angular/service-worker/config/schema.json",  
  3.   "index""/index.html",  
  4.   "assetGroups": [  
  5.     {  
  6.       "name""app",  
  7.       "installMode""prefetch",  
  8.       "resources": {  
  9.         "files": [  
  10.           "/favicon.ico",  
  11.           "/index.html",  
  12.           "/manifest.webmanifest",  
  13.           "/*.css",  
  14.           "/*.js"  
  15.         ]  
  16.       }  
  17.     },  
  18.     {  
  19.       "name""assets",  
  20.       "installMode""lazy",  
  21.       "updateMode""prefetch",  
  22.       "resources": {  
  23.         "files": [  
  24.           "/assets/**",  
  25.           "/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"  
  26.         ]  
  27.       }  
  28.     }  
  29.   ]  
  30. }  
Step 5 
In the app.module.ts file, we already added the ServiceWorkerModule and enabled it for production only.
 
The module also refers to a file called ngsw-worker.js. This file is built by the CLI in production mode. Angular uses the configuration file for this process. In development mode, however, this file is not served so we should not enable the service worker for the development mode.
Now, we need to build the application by using the command –
  1. ng build –prod  
Now, the Angular Application project is ready to use the Angular Service Worker.
Because ng serve does not work with service workers, we must need to use a separate HTTP server to test our application locally. We can use any HTTP server. For example, we can use the http-server package from npm. To reduce the possibility of conflicts and avoid serving stale content, test on a dedicated port, and disable caching.
To serve the directory containing your web files with http-server, run the following command:
  1. http-server -p 8080 -c-1 dist/<project-name>  
With the server running, we can point your browser at http://localhost:8080/. Our application should load normally.
 
 
 
Now the If you want to block the network connection so that the chrome browser does not have any network access.
 
For applications that do not use the Angular service worker, refreshing now would display Chrome's Internet disconnected page that says "There is no Internet connection". With the addition of an Angular service worker, the application behavior changes. On a refresh, the page loads normally.
 
If you look at the Network tab, you can verify that the service worker is active.
 
 
 
Notice that under the "Size" column, the requests state is (from Service-Worker). This means that the resources are not being loaded from the network. Instead, they are being loaded from the service worker's cache.
 

Conclusion

 
In this article, we discussed how to implement the service-worker using the Angular Framework in any web application. Also, we discussed the basic concept of service workers along with configuration, how to enable, etc. I hope, this article will help you. Any feedback or query related to this article is most welcome.