English 中文(简体)
Service Workers and PWA
  • 时间:2024-09-17

Angular 8 - Service Workers and PWA


Previous Page Next Page  

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

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

Angular apppcation can be converted into PWA apppcation. To convert an Angular apppcation, we need to use service worker API. Service worker is actually a proxy server, which sits in between the browser, apppcation 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 apppcation 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 depvery − The apppcation needs to be depvered through HTTPS protocol. One exception of the https support is localhost for development purpose.

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

Create a new Angular apppcation 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 apppcation,


ng build --prod

PWA apppcation 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 apppcation as root folder.


f the apppcation 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 Offpne option.

Normal apppcation stops working if network is set to Offpne but, PWA apppcation works fine as shown below − PWA Advertisements