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.
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
JavaScript Service Worker Design Patterns for Better User Experience
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
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. 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
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. 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. 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. 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. 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. 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. Design Patterns
• Does not have to be app nor SPA!
• Different HTML when offline: https://
chris.bolin.co/offline
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
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. 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. 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.
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. 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
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. 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. 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. • 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.