Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

JavaScript Service Worker Design Patterns for Better User Experience

635 views

Published on

Not just for offline, JavaScript Service Workers give your web app a snappy response and predictable behavior. Your web app “feels like an app” to your more-satisfied users and stakeholders.

Published in: Software
  • Be the first to comment

  • Be the first to like this

JavaScript Service Worker Design Patterns for Better User Experience

  1. 1. JavaScript Service Worker Design Patterns for Better User Experience Doug Reeder reeder.29@gmail.com @reeder29 on Twitter https://hominidsoftware.com DougReeder on GitHub
  2. 2. Classical Request Path browser engine server proxy server cache Indexed DB cache classic proxy
  3. 3. What they are • Programmable network proxy • A separate thread, with separate context (like Web Workers) • Killed between events (don’t use globals) • Each origin may have multiple scopes • All tabs for pages in a scope share a single s.w. • Each s.w. may control multiple caches
  4. 4. What they can do • Intercept network requests, serve them from multiple sources & transform them • Access new Cache API • Construct responses using new Stream API • Can’t access DOM • Communicate via Requests, postMessage (structured clone of objects), IndexedDB & Cache API • Receive Web Push messages • [Chrome only] Background Sync: event when connectivity restored
  5. 5. New Request Path browser engine server proxy server cache service worker cache cache server Indexed DB Web Push
  6. 6. Why this matters 1: Network is the Enhancement • Latency not going away & bandwidth physics-limited • Lie-fi, erratic & costly cell data • Underprovisioned servers, activity surges, misconfigured routers • Resources & data can be immediately served from cache or IDB, then updated via network • Controlled caching: per-article, recent, predictive • Load-balance between continents
  7. 7. Why this is important 2: Threads & Streaming • More convenient than Web Workers for I/O transforms • Fetch JSON, xform to HTML • Crypto, other xforms • Move persistence layer to another thread • Unobtrusive analytics • UI stays snappy • Progressive rendering keeps users engaged
  8. 8. Why this is important 3: Sync with tab closed • Web Push: server pushes msg, OS+browser activates s.w. (& usually raises notification) • Store push payload in Indexed DB (typically) • Web page not loaded until user taps notification • [Chrome only] Background Sync when back online • Msg: store outbox in IDB, register for B.S.
  9. 9. Why this is important 4: Installability • PWA “Install to Homescreen” prompt • HTTPS • App Manifest • S.w. is most difficult prerequisite • User prompted to install only after he’s shown evidence of repeated use
  10. 10. Coding & Debugging • requires HTTPS - use surge.sh (or other) to test • Use ES 2016 • Register s.w. using requestIdleCallback() • Use service-worker-mock (on npm) to run unit tests in Node.js • close tab completely for new version; not reload
  11. 11. Caching Strategies • Cache only (e.g. static assets) like AppCache • Cache, fall back to network • Network, fall back to cache • Cache, then update (e.g. user avatars) • Cache, network update, refresh (requires postMessage)
  12. 12. Design Patterns • Does not have to be app nor SPA! • Different HTML when offline: https:// chris.bolin.co/offline
  13. 13. browser engine server proxy server cache service worker cache cache Offline/Nework-tolerant • S.w. pre-caches static assets on 1st load • On subsequent load, browser checks for updated s.w. If changed, deletes old cache, pre-caches new assets
  14. 14. • 2nd & later loads avoid network delay, flakiness; your app is never broken by a bad network • Basic data caching: • paths outside scope handled by classic proxy +cache • “network, fall back to cache” doesn’t require app logic to change
  15. 15. Offline Articles browser engine server proxy server cache service worker article cacheasset cache • Asset cache + 1/article; cache name is article title • In modern browsers, show “save for offline” button: add to cache in foreground • Default offline page lists caches, thus offline articles
  16. 16. • Like a podcatcher for the web; articles could include interactive demos, VR, AR, tools • Wifi-only tablet can hold conference schedule, guide to landmark or games for your kid
  17. 17. Load-Balancing Between Data Centers • Heuristics & hysteresis for server selection • Response time accounts for network congestion, server load browser engine serverservice worker server server
  18. 18. Revenant Multipage Site • DOM must be rebuilt & JS parsed on every navigation. • Page navigation requests full page HTML. For old browser, server returns previously concatenated <head> + header + footer + navigation + content.
  19. 19. browser engine server proxy server cache service worker cache cache • In new browser, s.w. intercepts, streams <head> + header + footer+ navigation from cache immediately, then content from cache or network.
  20. 20. • Browser displays content as it streams in • Network efficiency of Turbolinks, without dirty environment • Only 1 copy of common HTML • Can retrofit old site, if markup can be divided between fixed & variable parts
  21. 21. Greenfield Pattern: SPA w/ Search Repeater • UI like https://serenenotes.hominidsoftware.com/ • SPA requests search results HTML. For old browser, server converts DB result to HTML
  22. 22. browser engine server proxy server cache service worker Indexed DB • In modern browser, s.w. intercepts, queries Indexed DB & requests JSON from server • IDB results xformed to HTML • Server results de-duped, xformed, then update IDB
  23. 23. • Need code to xform objects to HTML in two places • Store 10,000 records locally, 10,000,000 on server, do full-text search & get recently accessed results right away
  24. 24. Indexed DB Centered • All data fits in Indexed DB • Foreground accesses Indexed DB • S.w. feeds Indexed DB browser engine server proxy serverservice worker Indexed DB Web Push
  25. 25. Where does this lead us? • Web apps w/ less friction & less session-oriented: • Snappy response at all times • UI & some content available immediately • Fire & forget editing • New content pushed; users don’t need to check in • Poor connections mean you’re (somewhat) out-of- date, not out-of-luck.
  26. 26. • When you’re offline, you can return to where you’ve been (or prepared to go), but can’t go someplace totally new • It’s easier to grab some content & unplug - to relax, or make a considered reply. • Whether people will choose to engage deliberately is unknown.
  27. 27. Questions?
  28. 28. Sites to try • offline app: 
 https://serenenotes.hominidsoftware.com • offline-only: https://chris.bolin.co/offline • service-worker-mock: https://github.com/ pinterest/service-workers/ • Is Service Worker Ready: https:// jakearchibald.github.io/isserviceworkerready/

×