SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Downloaden Sie, um offline zu lesen
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/

Weitere ähnliche Inhalte

Ähnlich wie JavaScript Service Worker Design Patterns for Better User Experience

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
 
SharePoint Saturday The Conference 2011 - SP2010 Performance
SharePoint Saturday The Conference 2011 - SP2010 PerformanceSharePoint Saturday The Conference 2011 - SP2010 Performance
SharePoint Saturday The Conference 2011 - SP2010 PerformanceBrian Culver
 
StackMate - CloudFormation for CloudStack
StackMate - CloudFormation for CloudStackStackMate - CloudFormation for CloudStack
StackMate - CloudFormation for CloudStackChiradeep Vittal
 
Kubernetes Architecture - beyond a black box - Part 1
Kubernetes Architecture - beyond a black box - Part 1Kubernetes Architecture - beyond a black box - Part 1
Kubernetes Architecture - beyond a black box - Part 1Hao H. Zhang
 
Service-Oriented Design and Implement with Rails3
Service-Oriented Design and Implement with Rails3Service-Oriented Design and Implement with Rails3
Service-Oriented Design and Implement with Rails3Wen-Tien Chang
 
Should you use HTML5 to build your product? The pros & cons of using current ...
Should you use HTML5 to build your product? The pros & cons of using current ...Should you use HTML5 to build your product? The pros & cons of using current ...
Should you use HTML5 to build your product? The pros & cons of using current ...boxuno
 

Ähnlich wie JavaScript Service Worker Design Patterns for Better User Experience (20)

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
 
SharePoint Saturday The Conference 2011 - SP2010 Performance
SharePoint Saturday The Conference 2011 - SP2010 PerformanceSharePoint Saturday The Conference 2011 - SP2010 Performance
SharePoint Saturday The Conference 2011 - SP2010 Performance
 
StackMate - CloudFormation for CloudStack
StackMate - CloudFormation for CloudStackStackMate - CloudFormation for CloudStack
StackMate - CloudFormation for CloudStack
 
Kubernetes Architecture - beyond a black box - Part 1
Kubernetes Architecture - beyond a black box - Part 1Kubernetes Architecture - beyond a black box - Part 1
Kubernetes Architecture - beyond a black box - Part 1
 
Service-Oriented Design and Implement with Rails3
Service-Oriented Design and Implement with Rails3Service-Oriented Design and Implement with Rails3
Service-Oriented Design and Implement with Rails3
 
Should you use HTML5 to build your product? The pros & cons of using current ...
Should you use HTML5 to build your product? The pros & cons of using current ...Should you use HTML5 to build your product? The pros & cons of using current ...
Should you use HTML5 to build your product? The pros & cons of using current ...
 

Kürzlich hochgeladen

Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 

Kürzlich hochgeladen (20)

Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 

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/