SlideShare a Scribd company logo
1 of 28
Download to read offline
JavaScript Service Worker
Design Patterns
for Better User Experience
Doug Reeder
reeder.29@gmail.com
@reeder29 on Twitter
https://hominidsoftware.com
DougReeder on GitHub
Classical Request Path
browser
engine
server
proxy
server
cache
Indexed
DB
cache
classic
proxy
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
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
New Request Path
browser
engine
server
proxy
server
cache
service
worker
cache
cache
server
Indexed
DB
Web Push
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
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
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.
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
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
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)
Design Patterns
• Does not have to be app nor SPA!
• Different HTML when offline: https://
chris.bolin.co/offline
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
• 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
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
• 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
Load-Balancing
Between Data Centers
• Heuristics & hysteresis for server selection
• Response time accounts for network
congestion, server load
browser
engine
serverservice
worker
server
server
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.
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.
• 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
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
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
• 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
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
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.
• 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.
Questions?
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/

More Related Content

Similar to JavaScript Service Worker Design Patterns for Better User Experience

Improve WordPress performance with caching and deferred execution of code
Improve WordPress performance with caching and deferred execution of codeImprove WordPress performance with caching and deferred execution of code
Improve WordPress performance with caching and deferred execution of codeDanilo Ercoli
 
Optimization of modern web applications
Optimization of modern web applicationsOptimization of modern web applications
Optimization of modern web applicationsEugene Lazutkin
 
CNIT 129S: Ch 3: Web Application Technologies
CNIT 129S: Ch 3: Web Application TechnologiesCNIT 129S: Ch 3: Web Application Technologies
CNIT 129S: Ch 3: Web Application TechnologiesSam Bowne
 
CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009Jason Davies
 
CNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application TechnologiesCNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application TechnologiesSam Bowne
 
Drupal is not your Website
Drupal is not your Website Drupal is not your Website
Drupal is not your Website Phase2
 
A Tale of 2 Systems
A Tale of 2 SystemsA Tale of 2 Systems
A Tale of 2 SystemsDavid Newman
 
Drupal Is Not Your Web Site
Drupal Is Not Your Web SiteDrupal Is Not Your Web Site
Drupal Is Not Your Web SitePhase2
 
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...SPTechCon
 
Boost the Performance of SharePoint Today!
Boost the Performance of SharePoint Today!Boost the Performance of SharePoint Today!
Boost the Performance of SharePoint Today!Brian Culver
 
SRV418 Deep Dive on Accelerating Content, APIs, and Applications with Amazon ...
SRV418 Deep Dive on Accelerating Content, APIs, and Applications with Amazon ...SRV418 Deep Dive on Accelerating Content, APIs, and Applications with Amazon ...
SRV418 Deep Dive on Accelerating Content, APIs, and Applications with Amazon ...Amazon Web Services
 
Enterprise WordPress - Performance, Scalability and Redundancy
Enterprise WordPress - Performance, Scalability and RedundancyEnterprise WordPress - Performance, Scalability and Redundancy
Enterprise WordPress - Performance, Scalability and RedundancyJohn Giaconia
 
SharePoint Saturday San Antonio: SharePoint 2010 Performance
SharePoint Saturday San Antonio: SharePoint 2010 PerformanceSharePoint Saturday San Antonio: SharePoint 2010 Performance
SharePoint Saturday San Antonio: SharePoint 2010 PerformanceBrian Culver
 
Top 10 HTML5 Features for Oracle Cloud Developers
Top 10 HTML5 Features for Oracle Cloud DevelopersTop 10 HTML5 Features for Oracle Cloud Developers
Top 10 HTML5 Features for Oracle Cloud DevelopersBrian Huff
 
SRV418 Deep Dive on Accelerating Content, APIs, and Applications with Amazon ...
SRV418 Deep Dive on Accelerating Content, APIs, and Applications with Amazon ...SRV418 Deep Dive on Accelerating Content, APIs, and Applications with Amazon ...
SRV418 Deep Dive on Accelerating Content, APIs, and Applications with Amazon ...Amazon Web Services
 
Architectures, Frameworks and Infrastructure
Architectures, Frameworks and InfrastructureArchitectures, Frameworks and Infrastructure
Architectures, Frameworks and Infrastructureharendra_pathak
 
Java-Web-Applications.pdf
Java-Web-Applications.pdfJava-Web-Applications.pdf
Java-Web-Applications.pdfssuserf2dc4c1
 

Similar to JavaScript Service Worker Design Patterns for Better User Experience (20)

Improve WordPress performance with caching and deferred execution of code
Improve WordPress performance with caching and deferred execution of codeImprove WordPress performance with caching and deferred execution of code
Improve WordPress performance with caching and deferred execution of code
 
Optimization of modern web applications
Optimization of modern web applicationsOptimization of modern web applications
Optimization of modern web applications
 
Remix
RemixRemix
Remix
 
CNIT 129S: Ch 3: Web Application Technologies
CNIT 129S: Ch 3: Web Application TechnologiesCNIT 129S: Ch 3: Web Application Technologies
CNIT 129S: Ch 3: Web Application Technologies
 
CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009CouchDB for Web Applications - Erlang Factory London 2009
CouchDB for Web Applications - Erlang Factory London 2009
 
CNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application TechnologiesCNIT 129S - Ch 3: Web Application Technologies
CNIT 129S - Ch 3: Web Application Technologies
 
Drupal is not your Website
Drupal is not your Website Drupal is not your Website
Drupal is not your Website
 
A Tale of 2 Systems
A Tale of 2 SystemsA Tale of 2 Systems
A Tale of 2 Systems
 
Drupal Is Not Your Web Site
Drupal Is Not Your Web SiteDrupal Is Not Your Web Site
Drupal Is Not Your Web Site
 
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
Tutorial, Part 2: SharePoint 101: Jump-Starting the Developer by Rob Windsor ...
 
Boost the Performance of SharePoint Today!
Boost the Performance of SharePoint Today!Boost the Performance of SharePoint Today!
Boost the Performance of SharePoint Today!
 
SRV418 Deep Dive on Accelerating Content, APIs, and Applications with Amazon ...
SRV418 Deep Dive on Accelerating Content, APIs, and Applications with Amazon ...SRV418 Deep Dive on Accelerating Content, APIs, and Applications with Amazon ...
SRV418 Deep Dive on Accelerating Content, APIs, and Applications with Amazon ...
 
Javascript for Wep Apps
Javascript for Wep AppsJavascript for Wep Apps
Javascript for Wep Apps
 
Enterprise WordPress - Performance, Scalability and Redundancy
Enterprise WordPress - Performance, Scalability and RedundancyEnterprise WordPress - Performance, Scalability and Redundancy
Enterprise WordPress - Performance, Scalability and Redundancy
 
20120306 dublin js
20120306 dublin js20120306 dublin js
20120306 dublin js
 
SharePoint Saturday San Antonio: SharePoint 2010 Performance
SharePoint Saturday San Antonio: SharePoint 2010 PerformanceSharePoint Saturday San Antonio: SharePoint 2010 Performance
SharePoint Saturday San Antonio: SharePoint 2010 Performance
 
Top 10 HTML5 Features for Oracle Cloud Developers
Top 10 HTML5 Features for Oracle Cloud DevelopersTop 10 HTML5 Features for Oracle Cloud Developers
Top 10 HTML5 Features for Oracle Cloud Developers
 
SRV418 Deep Dive on Accelerating Content, APIs, and Applications with Amazon ...
SRV418 Deep Dive on Accelerating Content, APIs, and Applications with Amazon ...SRV418 Deep Dive on Accelerating Content, APIs, and Applications with Amazon ...
SRV418 Deep Dive on Accelerating Content, APIs, and Applications with Amazon ...
 
Architectures, Frameworks and Infrastructure
Architectures, Frameworks and InfrastructureArchitectures, Frameworks and Infrastructure
Architectures, Frameworks and Infrastructure
 
Java-Web-Applications.pdf
Java-Web-Applications.pdfJava-Web-Applications.pdf
Java-Web-Applications.pdf
 

Recently uploaded

Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineeringssuserb3a23b
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 

Recently uploaded (20)

Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Software Coding for software engineering
Software Coding for software engineeringSoftware Coding for software engineering
Software Coding for software engineering
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
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
  • 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. • 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. 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. • 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.
  • 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. • 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
  • 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. • 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.
  • 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/