SlideShare a Scribd company logo
Service Workers
Bring your own magic
Jungkee Song
Github: @jungkees
Twitter: @jungkees
Google+: +JungkeeSong
See this slide with animation here!
Service Workers solve ..
● Offline usage
○ Offline-first
○ Sorry, no magic. Create your own!
■ Programmable cache control
■ Custom response - Constructor, IDB, etc.
● Background processing
○ Wanna do things while UA’s not running?
○ Push messages, Alarms (Task Scheduler),
BackgroundSync, etc.
Installed!
Work in progress
Activating!
https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html
https://github.com/slightlyoff/ServiceWorker
Work in progress
● Lifecycle events
Principles and Terms
● Runs on same origin
● Registration keyed by URL scope
● Document is controlled by matching SW
upon navigation
● Successfully installed worker is considered
worker in waiting
● Functional events
Are you online?
Navigation/Resource request
Page
Network fetch
Response
Are you sufficiently online?
Navigation/Resource request
Page
Network fetch
4XX
5XX
Timeout
DNS failure
fetch event
Have a Service Worker?
Navigation/Resource request
onfetch
Page
SW
Cache
self.caches.match(url)
Promise<response>
e.respondWith
(Promise<response>)
IDB
new Response({
status: 200,
body: { … }
})
Offline-first
fetch event
Now fallback to network with SW
Navigation/Resource request
onfetch
Page
SW
Cache
self.fetch(request)
self.caches.match(url)
Promise rejects
e.respondWith
(Promise<response>)
Offline-first
fetch event
Event-driven worker
Navigation/Resource request
onfetch
Page
SW
Cache
self.caches.match(url)
Promise<response>
e.respondWith
(Promise<response>)
Page Page
Navigation/Resource request
fetch event
e.respondWith
(Promise<response>)
Key concept
// scope defaults to "/*"
navigator.serviceWorker.register("/assets/v1/serviceworker.js").then(
function(serviceWorker) {
console.log("success!");
serviceWorker.postMessage("Howdy from your installing page.");
// To use the serviceWorker immediately, you might call
// window.location.reload()
}, function(why) {
console.error("Installing the worker failed!", why);
});
Registration
● In the page
“/*” /assets/v1/serviceworker.js
[ Registration map ]
Scope Script URL
Service Worker Lifecycle
Registration
● In the page
navigator.serviceWorker.register("/sw.js");
“/*” /sw.js
[ Registration map ]
Scope Script URL
“/foo/*” /foo/sw.js
“/*” /bar/sw.js
Service Worker Lifecycle
navigator.serviceWorker.register("/foo/sw.js", { scope: “/foo/*” });
navigator.serviceWorker.register("/bar/sw.js");
Installation
● Registration triggers installation of the SW
● UA fires install event to the installing
Service Worker
● The event handler may extend the lifetime
of SW for preparing its caches
Service Worker Lifecycle
Installation: oninstall
● In the Service Worker context
// caching.js
this.addEventListener("install", function(e) {
// Create a cache of resources. Begins the process of fetching them.
var shellResources = new Cache();
// The coast is only clear when all the resources are ready.
e.waitUntil(shellResources.add(
"/app.html",
"/assets/v1/base.css",
"/assets/v1/app.js",
"/assets/v1/logo.png",
"/assets/v1/intro_video.webm",
));
// Add Cache to the global so it can be used later during onfetch
self.caches.set("shell-v1", shellResources);
});
Service Worker Lifecycle
Programmable cache control
● new Cache()
[Constructor]
interface Cache {
Promise<AbstractResponse>
match((Request or ScalarValueString) request, optional QueryParams params);
Promise<sequence<AbstractResponse>>
matchAll((Request or ScalarValueString) request, optional QueryParams params);
Promise<any> add((Request or ScalarValueString)... requests);
Promise<any> put((Request or ScalarValueString) request, AbstractResponse response);
Promise<any>
delete((Request or ScalarValueString) request, optional QueryParams params);
Promise<any> each(CacheIterationCallback callback, optional object thisArg);
};
Service Worker Lifecycle
● Worker in waiting
○ Once self.oninstall() ends
○ So to speak, the installation successfully done
○ This is not yet controlling the documents in scope
● navigator.serviceWorker.controller
○ When all the active documents in scope unload
○ The worker in waiting becomes active worker
○ self.clients.reloadAll() works
○ event.replace() works
Have a controller yet?
Service Worker Lifecycle
● In the Service Worker context
this.addEventListener("fetch", function(e) {
// No "onfetch" events are dispatched to the ServiceWorker until it
// successfully installs.
// All operations on caches are async, including matching URLs, so we use
// Promises heavily. e.respondWith() even takes Promises to enable this:
e.respondWith(
caches.match(e.request).catch(function() {
return e.default();
}).catch(function() {
return caches.match("/fallback.html");
})
);
});
Handle a fetch: onfetch
Functional event processing
Fetch: navigation request
onfetch
sw.js
Cache
self.caches.match(url)
Promise<response>
e.respondWith
(Promise<response>)
“/*” /sw.js
[ Registration map ]
Scope Script URL
“/foo/*” /foo/sw.js
Page Hit “https://example.com/index.html
fetch event
Scope matching
Run SW
Functional event processing
Fetch: subresource request
onfetch
sw.js
Cache
self.caches.match(url)
Promise<response>
e.respondWith
(Promise<response>)
“/*” /sw.js
[ Registration map ]
Scope Script URL
“/foo/*” /foo/sw.js
Page
Fetch “https://example.com/img/flower.png
fetch event
Control
Run SW
Functional event processing
Updating triggered by
● Registration
● Automatic by UA
● Successful navigation matching
● self.update()
Service Worker Lifecycle
Updating
onfetch
sw-v2
Cache
self.caches.match(url)
Promise<response>
e.respondWith
(Promise<response>)
“/*” /sw-v1
[ Registration map ]
Scope active
fetch event
-
waiting
Page
sw-v1
_Update
_Install
Page
sw-v1
/sw-v2 /sw-v2-
Page
sw-v2
Fetch “https://example.com/img/flower.png
Run SW
Service Worker Lifecycle
Security
● Origin relativity
● Cross origin resource
● HTTPS-only?
○ Protect end users from man-in-the-middle attacks
○ Existing "playground" services (e.g. github.io) now
work with HTTPS
○ HTTPS is coming across much more of the web
quickly
○ Devtools can loosen the restriction for development
● Event-driven workers
○ Free to shutdown the worker when handler’s done
○ “Write your workers as though they will die after
every request”
● Keep the onactivate short
● Platform considerations
○ Enhance matching navigation
○ Events implicitly filter
○ Enhance startup
Performance
Is it ready for you?
● Chrome Canary
○ Partial under flag
○ chrome://flags/#enable-service-worker
● Firefox Nightly
○ Partial under flag
○ about:config > dom.serviceWorkers.enabled
● Stay alerted!
○ Jake’s “Is ServiceWorker ready?”
References and Practices
● Service Worker - first draft published - Jake
Archibald
● Specification
● Github’s explainer
● Github’s implementation considerations

More Related Content

PDF
Service Worker Presentation
PDF
Angular Advanced Routing
PPTX
Akka Actor presentation
PDF
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
PDF
Introduction to Spring WebFlux #jsug #sf_a1
PDF
PDF
Android Networking
PDF
Angular & RXJS: examples and use cases
Service Worker Presentation
Angular Advanced Routing
Akka Actor presentation
Reactive Card Magic: Understanding Spring WebFlux and Project Reactor
Introduction to Spring WebFlux #jsug #sf_a1
Android Networking
Angular & RXJS: examples and use cases

What's hot (20)

PDF
An introduction to Vue.js
PDF
introduction to Vue.js 3
PPTX
Introduction to Node js
ODP
An Introduction to Vuejs
PPTX
REST & RESTful Web Services
PDF
Introduction to Spring webflux
PPTX
Progressive Web Apps(PWA)
PPTX
PPTX
Angular 2.0 forms
PDF
Progressive web apps
PDF
VueJS Introduction
PPTX
Introduction to node.js
ODP
Basics of VueJS
PDF
Intro to vue.js
PDF
Introduction to WebSockets Presentation
PDF
Intro to Reactive Programming
PDF
Introducing Async/Await
PDF
Being Functional on Reactive Streams with Spring Reactor
PDF
Angular routing
PPTX
An introduction to Vue.js
introduction to Vue.js 3
Introduction to Node js
An Introduction to Vuejs
REST & RESTful Web Services
Introduction to Spring webflux
Progressive Web Apps(PWA)
Angular 2.0 forms
Progressive web apps
VueJS Introduction
Introduction to node.js
Basics of VueJS
Intro to vue.js
Introduction to WebSockets Presentation
Intro to Reactive Programming
Introducing Async/Await
Being Functional on Reactive Streams with Spring Reactor
Angular routing
Ad

Viewers also liked (12)

PPT
Service Workers for Performance
PDF
"Service Worker: Let Your Web App Feel Like a Native "
PPTX
Service workers your applications never felt so good
PPTX
Service workers - Velocity 2016 Training
PDF
Scalable Angular 2 Application Architecture
PPTX
Machine Learning RUM - Velocity 2016
PPTX
TLS - 2016 Velocity Training
PPTX
Progressive Web Apps [pt_BR]
PDF
Introduction to Progressive Web Apps, Google Developer Summit, Seoul - South ...
PDF
Introduction to Progressive web app (PWA)
PPT
Scaling Front-End Performance - Velocity 2016
PPTX
Progressive Web App
Service Workers for Performance
"Service Worker: Let Your Web App Feel Like a Native "
Service workers your applications never felt so good
Service workers - Velocity 2016 Training
Scalable Angular 2 Application Architecture
Machine Learning RUM - Velocity 2016
TLS - 2016 Velocity Training
Progressive Web Apps [pt_BR]
Introduction to Progressive Web Apps, Google Developer Summit, Seoul - South ...
Introduction to Progressive web app (PWA)
Scaling Front-End Performance - Velocity 2016
Progressive Web App
Ad

Similar to Service workers (20)

PDF
[1C1]Service Workers
PDF
Service Worker - Reliability bits
PDF
PWA Roadshow Korea - Service Worker
PDF
ServiceWorker: New game changer is coming!
PPTX
Offline First with Service Worker
PDF
JQuery UK Service Workers Talk
PDF
JQuery UK February 2015: Service Workers On Vacay
PPTX
Service workers and the role they play in modern day web apps
PPTX
Progressive Web Apps 101
PDF
PWA 與 Service Worker
PDF
Service worker: discover the next web game changer
PPTX
Building Offline Ready and Installable Web App
KEY
Writing robust Node.js applications
PDF
Service workers
PPTX
Building Progressive Web Apps for Windows devices
PDF
Tech friday 22.01.2016
PDF
HTML5: huh, what is it good for?
PDF
Building with Firebase
PDF
Serverless Java on Kubernetes
PDF
NodeJS
[1C1]Service Workers
Service Worker - Reliability bits
PWA Roadshow Korea - Service Worker
ServiceWorker: New game changer is coming!
Offline First with Service Worker
JQuery UK Service Workers Talk
JQuery UK February 2015: Service Workers On Vacay
Service workers and the role they play in modern day web apps
Progressive Web Apps 101
PWA 與 Service Worker
Service worker: discover the next web game changer
Building Offline Ready and Installable Web App
Writing robust Node.js applications
Service workers
Building Progressive Web Apps for Windows devices
Tech friday 22.01.2016
HTML5: huh, what is it good for?
Building with Firebase
Serverless Java on Kubernetes
NodeJS

More from jungkees (7)

PDF
Samsung Internet 4.0
PDF
Progressive Web Apps
PDF
Service Worker at W3C HTML5 Conference in Seoul on the 9th of Dec 2015
PDF
Service workers 기초 및 활용 (Korean)
PDF
Do you Promise?
ODP
Progress Events Web Apps F2F at San Jose
ODP
XHR Web APps F2F at San Jose
Samsung Internet 4.0
Progressive Web Apps
Service Worker at W3C HTML5 Conference in Seoul on the 9th of Dec 2015
Service workers 기초 및 활용 (Korean)
Do you Promise?
Progress Events Web Apps F2F at San Jose
XHR Web APps F2F at San Jose

Recently uploaded (20)

PPTX
L1 - Introduction to python Backend.pptx
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
iTop VPN Free 5.6.0.5262 Crack latest version 2025
PDF
Autodesk AutoCAD Crack Free Download 2025
PPTX
Computer Software and OS of computer science of grade 11.pptx
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
Patient Appointment Booking in Odoo with online payment
PPTX
AMADEUS TRAVEL AGENT SOFTWARE | AMADEUS TICKETING SYSTEM
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Cost to Outsource Software Development in 2025
PPTX
Reimagine Home Health with the Power of Agentic AI​
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PDF
How to Make Money in the Metaverse_ Top Strategies for Beginners.pdf
PPTX
Monitoring Stack: Grafana, Loki & Promtail
PPTX
history of c programming in notes for students .pptx
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
medical staffing services at VALiNTRY
L1 - Introduction to python Backend.pptx
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
iTop VPN Free 5.6.0.5262 Crack latest version 2025
Autodesk AutoCAD Crack Free Download 2025
Computer Software and OS of computer science of grade 11.pptx
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Patient Appointment Booking in Odoo with online payment
AMADEUS TRAVEL AGENT SOFTWARE | AMADEUS TICKETING SYSTEM
Operating system designcfffgfgggggggvggggggggg
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
wealthsignaloriginal-com-DS-text-... (1).pdf
Design an Analysis of Algorithms I-SECS-1021-03
Cost to Outsource Software Development in 2025
Reimagine Home Health with the Power of Agentic AI​
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
How to Make Money in the Metaverse_ Top Strategies for Beginners.pdf
Monitoring Stack: Grafana, Loki & Promtail
history of c programming in notes for students .pptx
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
medical staffing services at VALiNTRY

Service workers

  • 2. Jungkee Song Github: @jungkees Twitter: @jungkees Google+: +JungkeeSong See this slide with animation here!
  • 3. Service Workers solve .. ● Offline usage ○ Offline-first ○ Sorry, no magic. Create your own! ■ Programmable cache control ■ Custom response - Constructor, IDB, etc. ● Background processing ○ Wanna do things while UA’s not running? ○ Push messages, Alarms (Task Scheduler), BackgroundSync, etc.
  • 6. ● Lifecycle events Principles and Terms ● Runs on same origin ● Registration keyed by URL scope ● Document is controlled by matching SW upon navigation ● Successfully installed worker is considered worker in waiting ● Functional events
  • 7. Are you online? Navigation/Resource request Page Network fetch Response
  • 8. Are you sufficiently online? Navigation/Resource request Page Network fetch 4XX 5XX Timeout DNS failure
  • 9. fetch event Have a Service Worker? Navigation/Resource request onfetch Page SW Cache self.caches.match(url) Promise<response> e.respondWith (Promise<response>) IDB new Response({ status: 200, body: { … } }) Offline-first
  • 10. fetch event Now fallback to network with SW Navigation/Resource request onfetch Page SW Cache self.fetch(request) self.caches.match(url) Promise rejects e.respondWith (Promise<response>) Offline-first
  • 11. fetch event Event-driven worker Navigation/Resource request onfetch Page SW Cache self.caches.match(url) Promise<response> e.respondWith (Promise<response>) Page Page Navigation/Resource request fetch event e.respondWith (Promise<response>) Key concept
  • 12. // scope defaults to "/*" navigator.serviceWorker.register("/assets/v1/serviceworker.js").then( function(serviceWorker) { console.log("success!"); serviceWorker.postMessage("Howdy from your installing page."); // To use the serviceWorker immediately, you might call // window.location.reload() }, function(why) { console.error("Installing the worker failed!", why); }); Registration ● In the page “/*” /assets/v1/serviceworker.js [ Registration map ] Scope Script URL Service Worker Lifecycle
  • 13. Registration ● In the page navigator.serviceWorker.register("/sw.js"); “/*” /sw.js [ Registration map ] Scope Script URL “/foo/*” /foo/sw.js “/*” /bar/sw.js Service Worker Lifecycle navigator.serviceWorker.register("/foo/sw.js", { scope: “/foo/*” }); navigator.serviceWorker.register("/bar/sw.js");
  • 14. Installation ● Registration triggers installation of the SW ● UA fires install event to the installing Service Worker ● The event handler may extend the lifetime of SW for preparing its caches Service Worker Lifecycle
  • 15. Installation: oninstall ● In the Service Worker context // caching.js this.addEventListener("install", function(e) { // Create a cache of resources. Begins the process of fetching them. var shellResources = new Cache(); // The coast is only clear when all the resources are ready. e.waitUntil(shellResources.add( "/app.html", "/assets/v1/base.css", "/assets/v1/app.js", "/assets/v1/logo.png", "/assets/v1/intro_video.webm", )); // Add Cache to the global so it can be used later during onfetch self.caches.set("shell-v1", shellResources); }); Service Worker Lifecycle
  • 16. Programmable cache control ● new Cache() [Constructor] interface Cache { Promise<AbstractResponse> match((Request or ScalarValueString) request, optional QueryParams params); Promise<sequence<AbstractResponse>> matchAll((Request or ScalarValueString) request, optional QueryParams params); Promise<any> add((Request or ScalarValueString)... requests); Promise<any> put((Request or ScalarValueString) request, AbstractResponse response); Promise<any> delete((Request or ScalarValueString) request, optional QueryParams params); Promise<any> each(CacheIterationCallback callback, optional object thisArg); }; Service Worker Lifecycle
  • 17. ● Worker in waiting ○ Once self.oninstall() ends ○ So to speak, the installation successfully done ○ This is not yet controlling the documents in scope ● navigator.serviceWorker.controller ○ When all the active documents in scope unload ○ The worker in waiting becomes active worker ○ self.clients.reloadAll() works ○ event.replace() works Have a controller yet? Service Worker Lifecycle
  • 18. ● In the Service Worker context this.addEventListener("fetch", function(e) { // No "onfetch" events are dispatched to the ServiceWorker until it // successfully installs. // All operations on caches are async, including matching URLs, so we use // Promises heavily. e.respondWith() even takes Promises to enable this: e.respondWith( caches.match(e.request).catch(function() { return e.default(); }).catch(function() { return caches.match("/fallback.html"); }) ); }); Handle a fetch: onfetch Functional event processing
  • 19. Fetch: navigation request onfetch sw.js Cache self.caches.match(url) Promise<response> e.respondWith (Promise<response>) “/*” /sw.js [ Registration map ] Scope Script URL “/foo/*” /foo/sw.js Page Hit “https://example.com/index.html fetch event Scope matching Run SW Functional event processing
  • 20. Fetch: subresource request onfetch sw.js Cache self.caches.match(url) Promise<response> e.respondWith (Promise<response>) “/*” /sw.js [ Registration map ] Scope Script URL “/foo/*” /foo/sw.js Page Fetch “https://example.com/img/flower.png fetch event Control Run SW Functional event processing
  • 21. Updating triggered by ● Registration ● Automatic by UA ● Successful navigation matching ● self.update() Service Worker Lifecycle
  • 22. Updating onfetch sw-v2 Cache self.caches.match(url) Promise<response> e.respondWith (Promise<response>) “/*” /sw-v1 [ Registration map ] Scope active fetch event - waiting Page sw-v1 _Update _Install Page sw-v1 /sw-v2 /sw-v2- Page sw-v2 Fetch “https://example.com/img/flower.png Run SW Service Worker Lifecycle
  • 23. Security ● Origin relativity ● Cross origin resource ● HTTPS-only? ○ Protect end users from man-in-the-middle attacks ○ Existing "playground" services (e.g. github.io) now work with HTTPS ○ HTTPS is coming across much more of the web quickly ○ Devtools can loosen the restriction for development
  • 24. ● Event-driven workers ○ Free to shutdown the worker when handler’s done ○ “Write your workers as though they will die after every request” ● Keep the onactivate short ● Platform considerations ○ Enhance matching navigation ○ Events implicitly filter ○ Enhance startup Performance
  • 25. Is it ready for you? ● Chrome Canary ○ Partial under flag ○ chrome://flags/#enable-service-worker ● Firefox Nightly ○ Partial under flag ○ about:config > dom.serviceWorkers.enabled ● Stay alerted! ○ Jake’s “Is ServiceWorker ready?”
  • 26. References and Practices ● Service Worker - first draft published - Jake Archibald ● Specification ● Github’s explainer ● Github’s implementation considerations