PWA with Angular : Introduction

#22

Who am I ?

Even Stack Overflow can't answer!

Ajit Kumar Singh

Doing Software Stuff 

Doing frontend stuff.

I ❤️ web despite its weirdness, except 

Crying over NullPointers in Java

OUTLINE

  • PWA
  • Home screen installation
  • Giving offline capabilities
  • Angular PWA
  • What's the "cache" ? 🤨

PWA

Hype train is coming

Progressive

PWA

Web

+

Application

+

=

?

The buzzword

PWA

PWA are websites that use modern web capabilities to deliver a native app-like user experience.

The term PWA is like a quality stamp.

Communicates about a certain quality level, instead of some feature list or technical details.

PWA

Those who named it say that:

It’s just a useful term for a toolkit of features.

Alex Russell

The name isn’t for you […]

The name is for your boss, for your investor, for your marketeer.

Frances Berriman

... just a bunch of technologies with a zingy-new brandname that keeps the open web going a bit longer.....

Progressive enhancement

PWA

Web Application is what it really is.

A development approach, not a technology choice

Progressive is the keyword

Too Long; Didn't Listen

PWA

PWA

Benefits

  • Take advantage of open nature of web (No App Store & App Update Hassles)
  • Very small in size

     
  • Significant cut down page in load times
  • Offline Support for Website Users
Android PWA
Twitter 17.3 MB 1.3M
Google Map 25 MB 208k

I was too lazy to add more 😬

Business and market benefit stats: https://www.pwastats.com

PWA

Who is in the hype train?

Find more: https://appsco.pe

Very long checklist

PWA

Just enough to close the ticket needs...

PWA

  • Originate from a Secure Origin
  • Some installation information
  • Load while offline

To convert your web app to "appy-like" PWA:

(even if only a custom offline page)

HTTPS or localhost

Web App Manifest

Service Workers

WEB APP MANIFEST

What is it?

Simple JSON file that defines some key properties of PWA like

  • Name
  • Colors
  • Icons
  • ...and so on....

Metadata for PWA

WEB APP MANIFEST

Where does it go?

<!doctype html>
    <head>
        ...
      <link rel="manifest" href="manifest.webmanifest">
        ...
    </head>
    <body>
      ...
    </body>
</html>

index.html

WEB APP MANIFEST

Adding to home screen

{
  "name": "NG Leipzig PWA Demo",
  "short_name": "NG Leipzig",
  "theme_color": "#985151",
  "background_color": "#3b906a",
  "display": "standalone",
  "Scope": "/",
  "start_url": "/",
  "icons": [
    {
      "src": "assets/icons/icon-72x72.png",
      "sizes": "72x72",
      "type": "image/png"
    },
    .......
  ]
}

WEB APP MANIFEST

Splash screen

{
  "name": "NG Leipzig PWA Demo",
  "short_name": "NG Leipzig",
  "theme_color": "#985151",
  "background_color": "#3b906a",
  "display": "standalone",
  "Scope": "/",
  "start_url": "/",
  "icons": [
    {
      "src": "assets/icons/icon-72x72.png",
      "sizes": "72x72",
      "type": "image/png"
    },
    .......
  ]
}

WEB APP MANIFEST

Home screen

{
  "name": "NG Leipzig PWA Demo",
  "short_name": "NG Leipzig",
  "theme_color": "#985151",
  "background_color": "#3b906a",
  "display": "standalone",
  "Scope": "/",
  "start_url": "/",
  "icons": [
    {
      "src": "assets/icons/icon-72x72.png",
      "sizes": "72x72",
      "type": "image/png"
    },
    .......
  ]
}

WEB APP MANIFEST

I am lazy edition!

WEB APP MANIFEST

SERVICE WORKER

What is it?

Programmable network proxy that sits between the web page and the network.

( Good place for doing caching stuff )

SERVICE WORKER

Some facts

  • Runs separate thread from the UI
  • Do not require an open web page to work
  • They have a life cycle

SERVICE WORKER

Lifecycle

// Registration
if (navigator.serviceWorker) {
    navigator.serviceWorker.register('/serviceworker.js');
}

SERVICE WORKER

Start with registering a service worker

Lifecycle - Installation

Ideal time to cache some static assets.

👉

//Take care of precaching the resources we need.
self.addEventListener('install', event => {
    event.waitUntil(
        caches.open('cache-name')
        .then(cache => cache.addAll(PRECACHE_URLS))
    );
});

SERVICE WORKER

Installed if all the files are cached successfully.

Lifecycle - Activated

Ideal place for cleaning old caches from older service worker

👉

// The activate handler takes care of cleaning up old caches.
self.addEventListener('activate', event => {
  
    event.waitUntil(cleanCache());
  
});

SERVICE WORKER

Lifecycle - Termination

👉

* A user agent may terminate service workers at any time it:

  • Has no event to handle.

  • Detects abnormal operation: such as infinite loops and tasks exceeding imposed time limits (if any) while handling the events.

SERVICE WORKER

Lifecycle - Fetch

👉

self.addEventListener('fetch', event => event.respondWith(
    // Various caching strategies possible here
));

Service worker will begin to receive fetch events

SERVICE WORKER

Caching Flow

SERVICE WORKER

The most important thing you need to know is :

By using Service Worker Cache you are NOT disabling Browser Cache.

The basic flow is:

  1. Try Service Worker Cache, if found serve with it, else
  2. Try Browser Cache – if found serve with it, else 
  3. Fetch data from the server – if all else fails, reply with server data.

Service Worker can hijack any request.

Caching Strategies

Network First

self.addEventListener('fetch', event => event.respondWith(
  
   fromNetwork(event.request).catch(() => fromCache(event.request))
  
));
FRESHNESS

SERVICE WORKER

Caching Strategies

Stale-while-revalidate

self.addEventListener('fetch', function (event) {
  
  // answer immediately from cache
  event.respondWith(fromCache(event.request));
  
  // update the cache with network response for next time
  event.waitUntil(updateCache(event.request));
});
PERFORMANCE

SERVICE WORKER

ANGULAR PWA

Moment of truth!

ng new << YOUR PROJECT >>
ng add @angular/pwa
ng build --prod

ANGULAR PWA

What changed?

git status and git diff time

ANGULAR PWA

Angular PWA facts

  • one-size-fits-all” service worker
  • Configurable via file: ngsw-config.json

  • Enabled only on production builds!!!

ANGULAR PWA

Configuration

export interface Schema {
  appData?: {
    [k: string]: any;
  };
  index: string;
  assetGroups?: {
    name: string;
    installMode?: "prefetch" | "lazy";
    updateMode?: "prefetch" | "lazy";
    resources: {
      files?: string[];
      urls?: string[];
    };
  }[];
  dataGroups?: {
    name: string;
    urls: string[];
    version?: number;
    cacheConfig: {
      maxSize: number;
      maxAge: string;
      timeout?: string;
      strategy?: "freshness" | "performance";
    };
  }[];
  navigationUrls?: string[];
}

index: Usually this is /index.html

ANGULAR PWA

ngsw-config.json

assetGroups:  Static assets to cache

dataGroup:  API endpoints you want to cache

maxAge:  How long to cache

maxSize:  How many to cache; LRU caching

timeOut:  How long to wait in case of freshness strategy

navigationUrls: list of URLs that will be redirected to the index file

appData: Any data you want to add with this version of the app

files:  Your app static assets

urls:  URL to external static assets e.g. google fonts

How does it work?

ANGULAR PWA

Angular Service worker:

  • downloaded when the app is first opened or is used after long time ( based on HTTP cache headers  but 1 day max )
  • won't change with build (except for angular updates)

Checking for updates:

  1. User opens app or reloads

  2. Angular Service worker will look for updates to the ngsw.json

  3. If an update is found, it is downloaded and cached (Can listen to event with SwUpdate service)

  4. Updated version is served next time the application is loaded

Might save your Friday!

ANGULAR PWA

Bypassing the service worker: Set ngsw-bypass as a request header, or as a query parameter.

Value doesn't matter, can be empty.

Self-destruct​: Make ngsw.json return 404 (rename or delete it).

The service worker will remove all of its caches and de-registers itself.

WHAT'S THE "CACHE" ? 🤨

Can do all what web technologies allow.

Can ONLY do what web technologies allow.

What is the limit?

WHAT'S THE "CACHE" ? 🤨

  • have better performance than PWA   ( WebAssembly maybe...? 🤔🤔🤔 )
  • offer greater UX possibilities e.g. games, VR AR stuff

Please don't start A vs B fight

Native applications still:

PWA struggles:

  • with 🍎 👁️OS , link capturing, notifications etc*
  • because of browser compatibility mess

WHAT'S THE "CACHE" ? 🤨

Asking questions helps.

  • How is Internet quality of your target user base?
  • Do you already have a mobile optimised website?
  • Does your app require heavy processing powers?
  • Do you need platform-specific native features?
  • Can you wait or compromise with some features missing on 🍎 👁️OS?

and so on ..

WHAT'S THE "CACHE" ? 🤨

BACKLOG

BACKLOG

  • Service Worker deep dive
  • Push Notifications
  • App Shell
  • Background Sync
  • IndexedDB
  • CacheStorage API
  • App Install Banners
  • Workbox ??

What else ? 🤔

🙏THANKS 🙏

NEXT FREE 🍕 🍺             DAY

Where? Here                              
Does it has a name? Well dah!!  It's called software enthusiasts
What can I expect? 🍕 🍺 and awesome talks by awesome jambitees 😎
What awesome talks? All kinda tech stuff but first one will be about:

1. Modern React with Hooks by Santo Pfingsten, Software Engineer

2. An introduction to service meshes by Max Brenner, DevOps Engineer
When? Tuesday, November 26, 2019, 6:30 PM to 9:30 PM
I have more questions! Ask ​Philip Achenbach for more info and let me go now please 😰🙏
Made with Slides.com