François Facon

Ridae  Hamdani

 

Progressive Web Apps made easy with Angular

How to create an Angular Progressive Web App?

Natively & naturally

François Facon

@frafac

  • Web & Mobile Expert

  • Angular - OpenShift / Trainer

  • Software Development Community Office (SDCO)

Ridae Hamdani

@ridaehamdani

  • ENIB Student

  • Engineer  | multitasking Ninja | writer  and many other things
  • Software Development Community Office (SDCO)​

PWA

  1. Introduction
  2. The What,Which, Why and how questions
  3. The magic of Angular/PWA
  4. The dark side of PWA
  5. Conclusion

what is PWA?

Progressive web apps use modern web APIs along with traditional progressive enhancement strategy to create cross-platform web applications.

These apps work everywhere and provide several features that give them the same user experience advantages as native apps.

what is PWA?

PWA Features

Why using PWA ?

 

 

  • only HTML/CSS + JS
  • Linkability
  • Can be indexed by seach engines 
  • Easy installation and updates
  • No dowload required 

PWA advantages

One codebase for every plateform

Browser

Desktop

Mobile

App store

Dev builds

which PWA are out there ?

How to install PWA on Desktop

 

  1. open Chrome browser
  2. visite the website
  3. Open menu ( or enable the flag: chrome://flags/#enable-desktop-pwas)
  4. Click "Install <Your APP> "

How PWA works ?

Proper app experience

Web App Manifest

How PWA works ?

Working offline

Proper app experience

Smarter networking

}

Service Worker

API

Web App Manifest

How PWA works ?

Service worker is the backbone of PWA

PWA and modern UI frameworks

PWA has nothing to do with the framework you are using. You just need :   

     - Service worker

     - Manifest file
     - Served over HTTPS

 

❤

Angular Service Worker

NGSW

Generate  a new Angular PWA

$ ng new myPWA
  • Angular CLI > 6

$ ng add @angular/pwa --project=myPWA

Get the code from GitHub  &

Let's do "ng add @angular/pwa"

CREATE src/manifest.json

Text

Text

Text

is the ID card of the PWA

CREATE src/ngsw-config.json 

 this configuration file specifies which files and data URLs the Angular service worker should cache and how it should update the cached files and data.

Update  angular.json 

"serviceWorker": true,
"ngswConfigPath": "src/ngsw-config.json"
 "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",



              "buildOptimizer": true,

To enable serviceworker in production mode

Update  angular.json 

"src/manifest.json"
"build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ng2ecom",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets",
              
            ],
          ...  
          },

To add Manifest to the asset list

Update  package.json 

$ npm install @angular/service-worker --save

same result as following npm command

Registering NGSW

import { ServiceWorkerModule } from '@angular/service-worker';
import { environment } from '../environments/environment';
...
@NgModule({
  ...
  imports: [
    ...


  ]
})
export class AppModule { }
    ServiceWorkerModule.register('/ngsw-worker.js',
        { enabled: environment.production }),

app.module.ts

Building Angular PWA

$ ng build --prod

ngsw-worker.js

ngsw.json

dist/

Service worker build support in the CLI

Build

src/ngsw-config.json

dist/ngsw.json

Service worker build support in the CLI

Copy

ngsw-worker.js

dist/

node_modules/@angular...

Can be npm-scripted for legacy Angular CLIs!

Run your Angular PWA

$ npm install -g http-server

      Install http-server globally.

$ http-server -c-1 -P http://localhost:8080 .

 To launch the PWA from the dist folder just type 

Thanks to the -P option all request to your API will be proxied to http://localhost:8080

Run your Angular PWA

 "scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config ./proxy.json --live-reload false",
    ...
    
    ...
},

Or add the following script  in your package.json

 "start:prod": "ng build --prod && cd dist/ng2ecom && http-server -c-1 -P http://localhost:8080 .",
$ npm run start:prod

 To launch the PWA with a simple

Demo Time

Hint #1: Checking the status

https://yourwebsite.com/ngsw/state

NGSW Debug Info:

Driver state: NORMAL ((nominal))
Latest manifest hash: cd4716ff2d3e24f4292010c929ff429d9eeead73
Last update check: 9s215u

=== Version 34c3fd2361735b1330a23c32880640febd059305 ===

Clients: 7eb10c76-d9ed-493a-be12-93f305394a77

=== Version cd4716ff2d3e24f4292010c929ff429d9eeead73 ===

Clients: ee22d69e-37f1-439d-acd3-4f1f366ec8e1

=== Idle Task Queue ===
Last update tick: 4s602u
Last update run: 9s222u
Task queue:


Debug log:

App version updates

v1

v2

v1

v1

v2

Server

Browser

v2

Hint #2: Notify about updates

import { SwUpdate } from '@angular/service-worker';
constructor(private swUpdate: SwUpdate) {}
ngOnInit() {
    if (this.swUpdate.isEnabled) {
      this.swUpdate.available.subscribe(() => {
          if (confirm(`New version available. Load New Version?`)) 
            { window.location.reload(); }
       });
    }
}

updates.component.ts

Hint #3: Kill switch

1. Long way

ng build --prod --serviceWorker
...deploy

2. Short way

rm dist/ngsw.json
...deploy

NGSW configuration file

src/ngsw-config.json

{
  "index": "/index.html",
  "assetGroups": [...],
  "dataGroups": [...]
}

index: Specifies the file that serves as the index page to satisfy navigation requests.

assetGroups: Assets are resources that are part of the app version that update along with the app. They can include resources loaded from the page's origin as well as third-party resources loaded from CDNs and other external URLs.

App shell

assetGroups

{
    "name": "app",
    "installMode": "prefetch",
    "resources": {...}
}

The installMode determines how these resources are initially cached.

prefetch tells the Angular service worker to fetch every single listed resource while it's caching the current version of the app. This is bandwidth-intensive but ensures resources are available whenever they're requested, even if the browser is currently offline.

App shell resources

assetGroups / "app" / resources

"resources": {







}
 "files": [
       "/favicon.ico",
       "/index.html",
       "/*.css",
       "/*.js"
     ]

App shell / on-demand

assetGroups

{
    "name": "assets",
    "installMode": "lazy",
    "updateMode": "prefetch",
    "resources": {...}
}

The installMode determines how these resources are initially cached.

lazy does not cache any of the resources up front. Instead, the Angular service worker only caches resources for which it receives requests. This is an on-demand caching mode. Resources that are never requested will not be cached.

App shell / on-demand

assetGroups

{
    "name": "assets",
    "installMode": "lazy",
    "updateMode": "prefetch",
    "resources": {...}
}

For resources already in the cache, the updateMode determines the caching behavior when a new version of the app is discovered.

prefetch tells the service worker to download and cache the changed resources immediately.

App shell / on-demand

assetGroups / "assets" / resources

"resources": {








}
    "files": [
      "/assets/**"
    ],
    "urls": [
        "https://fonts.googleapis.com/**",
        "https://fonts.gstatic.com/**"
    ]

Runtime caching

dataGroups

{
    "name": "api-performance-data",
    "urls": ["data/**"],



}

Data requests are cached according to manually-configured policies

urls : URLs that match these patterns will be cached according to this policy.

Cache config

dataGroups

{
    "name": "api-performance-data",
    "urls": ["data/**"],



}
"cacheConfig" : { "maxSize":1000, "maxAge":"3d",
                  "timeout":"10s", "strategy":"performance"}

Cache Config : This section defines the policy by which matching requests will be cached.

maxSize : (required) The maximum number of entries, or responses, in the cache.

maxAge : (required) how long responses are allowed to remain in the cache.

timeout : how long the service worker will wait for response before using cache.

Strategy

dataGroups

{
    "name" : "api-freshness-news",
    "urls" : [ "api/**" ],



}
"cacheConfig" : { "maxSize":1000, "maxAge":"1d",
                  "timeout":"10s", "strategy":"freshness"}

The Angular service worker can use either of two caching strategies for data resources.

performance : If a resource exists in the cache, the cached version is used, and no network request is made. 

freshness : optimizes for currency of data, preferentially fetching requested data from the network.

Demo

Angular Service Worker advantages

  • Essential features are config-driven

  • Decoupled updates model

  • Integrity checks

  • Doing things in Angular way

Some Tools and libraries

LightHouse

=>

Some Tools and libraries

JavaScript Libraries for adding offline support to web apps

workbox

Some Tools and libraries

A set of modules for different programming languages that make easy to send push messages

Web-push libs

The dark side of PWA's

  • LEGACY Browsers
     
  • Facebook and Google login can not fetch data from the native apps
     
  • No add to home screen prompt in IOS 

 

The dark side of PWA's

Web Notification

 

 

The dark side of PWA's

Push API 

 

 

What's coming next ?

2

Thank you!

François Facon

Ridae  Hamdani

 

Kudos to @webmaxru for the inspiration

Made with Slides.com