PWA Primer

Introduction and mindset presentation for writing PWA applications.

by Gion Kunz

What is PWA?

PWA is the future!

Who is using PWA?

  • Twitter Lite
  • Starbucks
  • Uber
  • Pinterest
  • Spotify
  • many more...
  • Progressive - Work for every user, regardless of browser choice because they’re built with progressive enhancement as a core tenet.
  • Responsive - Fit any form factor, desktop, mobile, tablet, or whatever is next.
  • Connectivity independent - Enhanced with service workers to work offline or on low quality networks.
  • App-like - Use the app-shell model to provide app-style navigations and interactions.
  • Fresh - Always up-to-date thanks to the service worker update process.
  • Safe - Served via TLS to prevent snooping and ensure content hasn’t been tampered with.
  • Discoverable - Are identifiable as “applications” thanks to W3C manifests and service worker registration scope allowing search engines to find them.
  • Re-engageable - Make re-engagement easy through features like push notifications.
  • Installable - Allow users to “keep” apps they find most useful on their home screen without the hassle of an app store.
  • Linkable - Easily share via URL and not require complex installation.

To PWA OR NOT TO PWA?

How much PWA?

Technologies

  • Service Workers - Offline capabilities and updates
  • Web App Manifest - Application Meta Data
  • Cache API - Allows fast caching of HTTP Responses
  • IndexedDB - Client side storage for content
  • Notification API - Native system notifications
  • Push API - Receive server messages
  • Background Sync - Service workers sync in background

Service Workers

caniuse, July 2020, global 1%

  • Intercepts HTTP requests
  • Allows to cache responses 
  • Life-cycle Management
  • Runs in a different Thread than UI
  • Supports Push API* and Background Sync*

* In some browsers ;-)

navigator.serviceWorker
  .register('/sw.js', { scope: '/sw-example/' })
  .then(reg => {
    // Registration succeeded
  }).catch(error => {
    // Error
  });
// Install phase
self.addEventListener('install', event => {
  event.waitUntil(
    caches.open('v1').then(cache => {
      return cache.addAll([
        '/sw-examples/',
        '/sw-examples/index.html',
        '/sw-examples/style.css',
        '/sw-examples/app.js'
      ]);
    })
  );
});
// Fetch interception proxy, try cache, load and cache on miss
self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request)
      .then(response => {
        return response ||
          fetch(event.request).then(response => {
            caches.open('v1').then(cache =>
              cache.put(event.request, response.clone());
            );
            return response;
          });
  }));
});

Service worker Cache is Fast... REEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEALLY fast......

Twitter Lite Case Study

  • 65% increase in pages per session
  • 75% increase in Tweets sent
  • 20% decrease in bounce rate

Cache for SPeed, Cache for Offline!

Web App Manifest

caniuse, August 2018

  • Allows to specify meta-data which can be used by the OS
  • App specific settings (icons, title, links to app store etc.)
{
  "name": "HackerWeb",
  "short_name": "HackerWeb",
  "start_url": ".",
  "display": "standalone",
  "background_color" : "#fff" ,
  "description": "Simple HackerNews Web App.",
  "Icons": [{
    "src": "images/touch/homescreen48.png",
    "sizes": "48x48",
    "type": "image/png"
  }
.....

Microsoft Store auto discovery using Bing

  • A non-empty web app manifest file, with at minimum:
    • Name
    • Description
    • App icon icon that is at least 512 x 512 pixels
  • Unique core logic (not minimally modified code from an app boilerplate template)
  • To be served over a secure connection (HTTPS)
  • Service worker script(s)
  • To not violate any laws or Microsoft Store policies.

Background Sync

caniuse, July 2020, gloabl 1%

  • Keeps service worker running until connection is stable 
  • Executes callback which allows to store updates on server
  • Use the Notification API to notify user about progress

Add To Home Screen

caniuse, July 2020, gloabl 1%

  • Allows users to "install" a PWA to their OS
  • Extended reach and lower barrier to entry

Add to home screen in Chrome for Windows!

Best practices and patterns

PRPL is a pattern for structuring and serving Progressive Web Apps (PWAs), with an emphasis on the performance of app delivery and launch.

PRPL

  • Push critical resources for the initial URL route.
  • Render initial route.
  • Pre-cache remaining routes.
  • Lazy-load and create remaining routes on demand.

Service Worker Patterns

PWA needs proper design

  • What can be done offline and what not?
  • How do we guide the user through offline capabilities?
  • How do we solve synchronization issues?
  • How do we update old clients (and reeeeeeeally old clients)

Angular and PWA

  • CLI can manage your service worker including updates and automatic asset caching
  • CLI creates App Manifest
  • Perfectly matches the PRPL pattern
  • Build your App Shell in the index.html or use Server Side Rendering

Create a PWA Angular app

npm install -g @angular/cli
ng new example-pwa
cd example-pwa
ng add @angular/pwa

Follow PRPL Pattern with Lazy Loading and preload

@NgModule ({
  bootstrap: [AppComponent],
  imports: [
    RouterModule.forRoot(ROUTES, {
      preloadingStrategy: PreloadAllModules
    })
  ]
})
class MainModule {}

Conclusion

  • PWA is the future!
  • PWA is not a framework!
  • PWA is a set of concepts and best-practices supported by various web standards
  • Progressive enhancement and feature detection with graceful fallbacks
  • PWA technology support is getting better and better
  • Include PWA as a core concept at the earliest point in the project possible (analysis and design)

Let's create together.

Thanks!

PWA

By Gion Kunz

PWA

PWA Primer for people who never really looked into the concept and technologies.

  • 697