Monthly Archives: February 2020

Angular – Progressive Web Apps using Service Workers

Angular – Progressive Web Apps using Service Workers

Service workers enable creating progressive web applications. It is a script running in the web browser supporting caching of the application resources. They preserve the resources even after the user closes the tab and serves them when the application is requested again.

Setting up Angular Project

Let’s first create a sample angular app.

We can use ng serve to verify that the application has been created successfully.

We can open the application in the web browser and it does load successfully.

It must be remembered that ng serve does not work with service workers so we need to host the application externally through a web server. Let’s use http-server for this. It can simply be installed through npm.

Just make sure that you are able to run it successfully:

Now let’s run our sample PWA app using http-server. Here -c-1 would disable caching.

Adding Service Worker Support

Let’s first verify that our application couldn’t be served offline. We can set the browser to appear as offline through Chrome Dev Tools.

Now we can add support for service worker by adding @angular/pwa.

As we build the application using ng build –prod, we can see that the browser is able to load the application offline using Service Worker.

We can also see Network tab to see service worker in action: