SlideShare a Scribd company logo
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

PDF
Relatório plano de aula de história
PPT
História da arte - Os ismos - Movimentos da Arte Moderna
PPT
PROJETO ARTE DENTRO DA ESCOLA - RELEITURA DAS OBRAS DE ROMERO BRITO
PDF
Questionário 1 professor
PDF
Apostila de Artes Visuais (revisada e ampliada 2014)
PPT
Projeto Orgulho de ser sulmatogrossense
PDF
Aula de Pintura
PPT
Modernismo 8ºano
Relatório plano de aula de história
História da arte - Os ismos - Movimentos da Arte Moderna
PROJETO ARTE DENTRO DA ESCOLA - RELEITURA DAS OBRAS DE ROMERO BRITO
Questionário 1 professor
Apostila de Artes Visuais (revisada e ampliada 2014)
Projeto Orgulho de ser sulmatogrossense
Aula de Pintura
Modernismo 8ºano

What's hot (20)

PPTX
Aula de endometriose versao 3
PPTX
FOLGUEDOS DO MASTRO CAPELA.pptx
PDF
Atividades sociologia trabalho lei de estágio e trabalho com carteira assinada
PPSX
Aula 01 introdução a arte como experiência
DOC
30.projeto cores formas_maternal_ii
PDF
Serie aula nota_10 , de Doug Lemov.
DOC
Atividade avaliativa sobre o filme Mãos Talentosas
DOCX
Modelo do plano de aula AEE TEA
DOC
Ata da eleição de lider e vice lider de turma
PDF
Autismo-programa-de-educacao-individualizada-PEI
PDF
Plano de ensino bimestral modelo
PPTX
Descolonização da África e da Ásia -Exercícios de fixação
PDF
Slide7 atividades circenses
PPTX
Diversidade social
PPTX
Aula de arte urbana
PDF
Regras comuns, diferentes cartazes
DOCX
Palavras cruzadas
PDF
Distribuição espacial da indústria
DOC
Roteiro museu
PPTX
Slide música – estilos e gêneros musicais diversos
Aula de endometriose versao 3
FOLGUEDOS DO MASTRO CAPELA.pptx
Atividades sociologia trabalho lei de estágio e trabalho com carteira assinada
Aula 01 introdução a arte como experiência
30.projeto cores formas_maternal_ii
Serie aula nota_10 , de Doug Lemov.
Atividade avaliativa sobre o filme Mãos Talentosas
Modelo do plano de aula AEE TEA
Ata da eleição de lider e vice lider de turma
Autismo-programa-de-educacao-individualizada-PEI
Plano de ensino bimestral modelo
Descolonização da África e da Ásia -Exercícios de fixação
Slide7 atividades circenses
Diversidade social
Aula de arte urbana
Regras comuns, diferentes cartazes
Palavras cruzadas
Distribuição espacial da indústria
Roteiro museu
Slide música – estilos e gêneros musicais diversos
Ad

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

PDF
Service worker API
PDF
Service workers are your best friends
PDF
Always on! ... or not?
PDF
Web fundamentals
PDF
A year with progressive web apps! #DevConMU
PDF
Service workers
PDF
A year with progressive web apps! #webinale
PPTX
Progressive web applications
PPTX
Raising ux bar with offline first design
PPTX
PWA basics for developers
PDF
Frontend. Global domination.
PDF
Front-end. Global domination
PPTX
HTML5 on Mobile
PDF
Always on! Or not?
PDF
APIs for modern web apps
PDF
"Progressive Web Apps" by Riza Fahmi (Hacktiv8)
PDF
Progressive Web Apps. What, why and how
PDF
Progressive Web Apps
PDF
APIs, now and in the future
PPTX
Service workers and their role in PWAs
Service worker API
Service workers are your best friends
Always on! ... or not?
Web fundamentals
A year with progressive web apps! #DevConMU
Service workers
A year with progressive web apps! #webinale
Progressive web applications
Raising ux bar with offline first design
PWA basics for developers
Frontend. Global domination.
Front-end. Global domination
HTML5 on Mobile
Always on! Or not?
APIs for modern web apps
"Progressive Web Apps" by Riza Fahmi (Hacktiv8)
Progressive Web Apps. What, why and how
Progressive Web Apps
APIs, now and in the future
Service workers and their role in PWAs
Ad

Recently uploaded (20)

PDF
System and Network Administraation Chapter 3
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
top salesforce developer skills in 2025.pdf
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
AI in Product Development-omnex systems
PPTX
Transform Your Business with a Software ERP System
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PPTX
Essential Infomation Tech presentation.pptx
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
ai tools demonstartion for schools and inter college
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
System and Network Administraation Chapter 3
Wondershare Filmora 15 Crack With Activation Key [2025
top salesforce developer skills in 2025.pdf
Which alternative to Crystal Reports is best for small or large businesses.pdf
Odoo POS Development Services by CandidRoot Solutions
wealthsignaloriginal-com-DS-text-... (1).pdf
Adobe Illustrator 28.6 Crack My Vision of Vector Design
AI in Product Development-omnex systems
Transform Your Business with a Software ERP System
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Essential Infomation Tech presentation.pptx
How to Choose the Right IT Partner for Your Business in Malaysia
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
ai tools demonstartion for schools and inter college
Understanding Forklifts - TECH EHS Solution
VVF-Customer-Presentation2025-Ver1.9.pptx
Navsoft: AI-Powered Business Solutions & Custom Software Development

JavaScript Service Worker Design Patterns for Better User Experience

  • 1. JavaScript Service Worker Design Patterns for Better User Experience Doug Reeder [email protected] @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/