Angular 8 – Service Workers and PWA

Progressive web apps (PWA) are normal web application with few enhancements and behaves like a native application. PWA apps does not depends on network to work. PWA caches the application and renders it from local cache. It regularly checks the live version of the application and then caches the latest version in the background.

PWA can be installed in the system like native application and shortcut can be shown in the desktop. Clicking the shortcut will open the application in browser with local cache even without any network available in the system.

Angular application can be converted into PWA application. To convert an Angular application, we need to use service worker API. Service worker is actually a proxy server, which sits in between the browser, application and the network.

Service workers is separate from web pages. It does not able to access DOM objects. Instead, Service Workers interact with web pages through PostMessage interface.

PWA application has two prerequisites. They are as follows,

  • Browser support − Even though lot of browser supports the PWA app, IE, Opera mini and few other does not provides the PWA support.
  • HTTPS delivery − The application needs to be delivered through HTTPS protocol. One exception of the https support is localhost for development purpose.

Let us create a new application and convert it into PWA application.

Create a new Angular application using below command −

cd /go/to/workspace 
ng new pwa-sample

Add PWA support using below command −

cd pwa-sample
ng add @angular/pwa --project pwa-sample

Build the production version of the application,

ng build --prod

PWA application does not run under Angular development server. Install, a simple web server using below command −

npm install -g http-server

Run the web server and set our production build of the application as root folder.

f the application as root folder.
http-server -p 8080 -c-1 dist/pwa-sample

Open browser and enter http://localhost:8080.

Now, go to Developer tools -> Network and select Offline option.Normal application stops working if network is set to Offline but, PWA application works fine as shown below −

PWA

Leave a Reply