Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Fast, offline-first PWA with Workbox

Avatar for Eka Eka
February 27, 2021

Fast, offline-first PWA with Workbox

An introductory talk about PWAs, Service Workers, and why and how to add Workbox to your PWA.

Presented at Chrome Dev Summit Extended GDG Cebu (Virtual), 27 February 2021

Avatar for Eka

Eka

February 27, 2021

More Decks by Eka

Other Decks in Programming

Transcript

  1. Progressive Web Apps “Websites that took all the right vitamins”

    Web applications + progressive enhancement with modern web APIs Capable, Reliable, Installable Not concerned with specific web stacks (frameworks, client/server-rendered)
  2. Progressive Web Apps Capabilities of native apps + reach of

    web apps Improve performance and user experience Increase user retention and conversion Can be packaged as Trusted Web Apps
  3. Capable Various modern web APIs make it possible for web

    apps to provide native-like features & capabilities See: whatpwacando.today
  4. Each browser has their own criteria; similar basic requirements Chrome

    (Feb 2021): - Meets a user engagement heuristic - HTTPS - Web App Manifest - Service Worker Installable Example from web.dev/add-manifest
  5. Fast and dependable, regardless of the network No blank page

    or default offline page, no silent failures or crashes. Important or relevant content always available. The Service Worker API is used to achieve this Reliable Image source: blog.sessionstack.com/how-javascript-works-service-workers-their-life-cycle-and- use-cases-52b19ad98b58
  6. Web browsers are single threaded (limitations: blocking, tab has to

    be open) Worker runs in a separate background thread (see: Web Workers API) Service Worker is a subset of Web Worker registered against an origin and a path “[A service worker] takes the form of a JavaScript file that can control the web-page/site that it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to give you complete control over how your app behaves in certain situation” — MDN Service Worker
  7. Workbox A set of libraries to write and manage service

    workers and caching Best practices, common scenarios, and advanced customization (extendable strategies; plugins) “FW for our SW”
  8. How to use Workbox in our web app? 1. (a)

    Load from CDN, or (b) Integrate to build process 2. Register the service worker 3. Create/modify our service worker 4. Build it
  9. The quickest and most simple start Works in any environment,

    including plain static HTML & JS Caveats: Have to load entire bundle No automatic precaching How to use Workbox? 1a. Load from CDN
  10. How to use Workbox? 1b. Integrate to build process -

    workbox-cli - workbox-build - workbox-webpack-plugin - workbox-window GenerateSW - generate a service worker file and write to disk - simple runtime config InjectManifest - generate list of URLs to precache; add it to existing service worker - use this if using service worker with other APIs / additional scripts
  11. How to use Workbox? 2. Register service worker Register the

    build service worker file (not the source!) on your web page If using a frontend framework, make sure to do this in the HTML template or in a mounted component
  12. How to use Workbox? 3. Create/modify service worker with workbox

    packages Examples in next slide: workbox-core workbox-precaching workbox-routing workbox-strategies workbox-cacheable-response workbox-expiration workbox-background-sync source service worker file example
  13. Example 0: workbox-core skipWaiting = publish a new service worker

    clientClaim = have it update and control a web page as soon as possible
  14. Example 2: workbox-routing workbox-strategies Use if you want to… implement

    common caching strategies by routes (eg. specific URLs/paths or request destination) Currently 5 strategies are available. More on the strategies: web.dev/offline-cookbook
  15. Example 2a: workbox-routing registerRoute(capture, handler, method = "GET") capture can

    be a string, regular expression, or callback function returning truthy value The callback function gets an argument that consists of: developer.mozilla.org/en-US/docs/We b/API/URL developer.mozilla.org/en-US/docs/We b/API/Request developer.mozilla.org/en-US/docs/We b/API/Event
  16. registerRoute(capture, handler, method = "GET") handler callback function that returns

    a Response object We can pass a workbox strategy or any custom handler function Example 2a: workbox-routing
  17. instantiate a new strategy object with options: new CacheFirst(options) options

    consist of cacheName and plugins (an array of plugin objects) plugins customize behaviors by manipulating responses and requests during the lifecycle of a request Currently there are 5 plugins Example 2b: workbox-strategies with plugins
  18. Use if you want to… retry a request and receive

    an event when network connection is restored after a failed request to the network Example: Chrome search bar Related web API: BackgroundSync github.com/WICG/background-sync Example 3: workbox- background- sync
  19. Example 3: workbox-background-sync LEFT: complete BackgroundSyncPlugin implementation with options passed

    to defined POST routes RIGHT: event listener code in our page/layout component
  20. Use if you want to… Implement common routing and caching

    patterns in one-line functions with sensible defaults Currently 6 recipes are available. Example 4: workbox-recipes
  21. Example 4: Offline Fallback from workbox-recipes LEFT: do the same

    thing with workbox-routing setCatchHandler RIGHT: offlineFallback recipe
  22. Workbox provides ready-to-use wrappers for common use cases and extendable

    classes for less common ones Less time on redundant boilerplate code, focus on features, ie. PWA best practices Less friction to give user a faster, more resilient and delightful web experience