Overview
Here we are going to add PWA features to our application Contact Book which we created previously in PART 1 with Angular 7 . We added native features to application like splash screen, offline support and sharing data on any social media. Get a popup to add to Home screen when user sees your application from mobile device.
Install & add angular/pwa
In angular 7, we have a feature to generate PWA files automatically and all its dependency.
PWA version is 0.7.4.
ng add @angular/pwa
Installed packages for tooling via npm.
CREATE ngsw-config.json (392 bytes) CREATE src/assets/icons/icon-128x128.png (1253 bytes) CREATE src/assets/icons/icon-144x144.png (1394 bytes) CREATE src/assets/icons/icon-152x152.png (1427 bytes) CREATE src/assets/icons/icon-192x192.png (1790 bytes) CREATE src/assets/icons/icon-384x384.png (3557 bytes) CREATE src/assets/icons/icon-512x512.png (5008 bytes) CREATE src/assets/icons/icon-72x72.png (792 bytes) CREATE src/assets/icons/icon-96x96.png (958 bytes) CREATE src/manifest.json (1083 bytes) UPDATE angular.json (3563 bytes) UPDATE package.json (1388 bytes) UPDATE src/app/app.module.ts (526 bytes) UPDATE src/index.html (390 bytes)
The command generates all of the dependencies installed for PWA support, also create default service-worker config file, and default manifest.json file and even default icons for your splash screen and mobile home screen. You can edit these files as per your need.
Now you app is ready to be build.
ng build --prod
Your app with service worker & manifest file is ready to deploy. Service worker cache CSS/SCSS, JS, assets and index.html file. It is only working for production builds because caching Javascript is not working in development mode, where live debugging might be needed.
iOS Support
For Android, it will take a support of manifest file but ios will not support manifest file. We have to add the following meta tag in index.html manually.
<meta name="apple-mobile-web-app-capable" content="yes"> // by default it will take app title <meta name="apple-mobile-web-app-title" content="My Contact App"> //by default it will take a screenshoot of app as a logo <meta name="apple-touch-icon" href="assets/icons/icon-192x192.png" sizes="180x180"> <meta name="apple-touch-icon" href="assets/icons/icon-128x128.png" sizes="120x120"> //by default ios have square logo so in blank space it will take black color <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
Inviting User To Install App
Invite the user to add our application to the home screen, we need the following code in app.component.ts.
ngOnInit(){ if ((navigator as any).standalone === false) { this.snackbar.open("You can add this to the Home Screen", '', { duration: 3000 }); } if ((navigator as any).standalone == undefined) { if (window.matchMedia("(display-mode:browser").matches) { // in browser window.addEventListener('beforeinstallprompt', event => { event.preventDefault(); const snackbar = this.snackbar.open("Do you want to install this App?", "Install ", { duration: 5000 }); sb.onAction().subscribe(() => { (event as any).prompt(); (event as any).userChoice.then(result => { if (result.outcome == 'dismissed') { console.log("Dismissed"); } else { console.log("Installed"); } }) }) return false; }) } } }
Service Worker
According to Google,
“A service worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don’t need a web page or user interaction.”
For the earlier version of PWA, we need to add Service worker via npm module. For the newer version, it will automatically be installed. For configuration of a service worker, we have the ngsw-config.json file.
npm install --save service-worker
Offline Support
We need to give our application an offline support. The user can use even if there’s no internet connection. So for that, we need to add a new file in root folder ngsw-manifest.json. In this file, we will add routing for our application in JSON format for offline support.
{ "routing": { "index": "/index.html", "routes": { "/": { "match": "exact" }, "/contact": { "match": "prefix" } } }, "static.ignore": [ "6\/icones\/.*$" ],
Here, we will add external links which are users in our application.
"external": { "urls": [ { "url": "https://fonts.googleapis.com/icon?family=Material+Icons" }, { "url": "https://fonts.gstatic.com/s/materialicons/v38/flUhRq6tzZclQEJ-Vdg-IuiaDsNcIhQ8tQ.woff2" } ] },
Here, we will serve dynamic content & cache in our application.
"dynamic": { "group": [ { "name": "api", "urls": { "http://localhost:3000/contacts": { "match": "prefix" } }, "cache": { "optimizeFor": "fressness", "networkTimeoutMs": 1000, "maxEntries": 30, "strategy": "lru", "maxAgeMs": 360000000 } } ] } }
Update UI When Network Status Change
Now we want to change UI when user goes online and offline for that we need to add the following code in app.component.ts.
updateNetworkStatusUI() { if (navigator.onLine) { (document.querySelector("body") as any).style = ""; } else { (document.querySelector("body") as any).style = "filter:grayscale(1)"; } } ngOnInit() { //check network status this.updateNetworkStatusUI(); window.addEventListener("online", this.updateNetworkStatusUI); window.addEventListener("offline", this.updateNetworkStatusUI); }
Check Audit
First we need to create a build in production mode by ng build –prod. Then we can check out how our application is going on. All we need to do is open the Chrome DevTools move to Audits tab, where you can find a very powerful tool as Lighthouse— the best diagnostics of web pages. Now press Perform an Audit. it will take some time, then we will get some results. The result looks good. Here we can see the increased PWA score.
Conclusion
Finally, Our app is ready to work in mobile device as Progressive Web Application(PWA) with Angular 7.