SlideShare une entreprise Scribd logo
1  sur  26
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introductionRasheed Waraich
 
AEM Sightly Deep Dive
AEM Sightly Deep DiveAEM Sightly Deep Dive
AEM Sightly Deep DiveGabriel Walt
 
Spring boot
Spring bootSpring boot
Spring bootsdeeg
 
개발자를 위한 (블로그) 글쓰기 intro
개발자를 위한 (블로그) 글쓰기 intro개발자를 위한 (블로그) 글쓰기 intro
개발자를 위한 (블로그) 글쓰기 introSeongyun Byeon
 
Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with JestMichał Pierzchała
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with SpringJoshua Long
 
AEM Best Practices for Component Development
AEM Best Practices for Component DevelopmentAEM Best Practices for Component Development
AEM Best Practices for Component DevelopmentGabriel Walt
 
Angular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdfAngular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdfJohnLeo57
 
Introduction To Single Page Application
Introduction To Single Page ApplicationIntroduction To Single Page Application
Introduction To Single Page ApplicationKMS Technology
 
AEM Sightly Template Language
AEM Sightly Template LanguageAEM Sightly Template Language
AEM Sightly Template LanguageGabriel Walt
 
HTL(Sightly) - All you need to know
HTL(Sightly) - All you need to knowHTL(Sightly) - All you need to know
HTL(Sightly) - All you need to knowPrabhdeep Singh
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.boyney123
 
TF에서 팀 빌딩까지 9개월의 기록 : 성장하는 조직을 만드는 여정
TF에서 팀 빌딩까지 9개월의 기록 : 성장하는 조직을 만드는 여정TF에서 팀 빌딩까지 9개월의 기록 : 성장하는 조직을 만드는 여정
TF에서 팀 빌딩까지 9개월의 기록 : 성장하는 조직을 만드는 여정Seongyun Byeon
 
Saving Time By Testing With Jest
Saving Time By Testing With JestSaving Time By Testing With Jest
Saving Time By Testing With JestBen McCormick
 
Spring Boot & Actuators
Spring Boot & ActuatorsSpring Boot & Actuators
Spring Boot & ActuatorsVMware Tanzu
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 formsEyal Vardi
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - DirectivesWebStackAcademy
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 

Tendances (20)

Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
AEM Sightly Deep Dive
AEM Sightly Deep DiveAEM Sightly Deep Dive
AEM Sightly Deep Dive
 
Spring boot
Spring bootSpring boot
Spring boot
 
Web workers
Web workersWeb workers
Web workers
 
개발자를 위한 (블로그) 글쓰기 intro
개발자를 위한 (블로그) 글쓰기 intro개발자를 위한 (블로그) 글쓰기 intro
개발자를 위한 (블로그) 글쓰기 intro
 
Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with Jest
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
AEM Best Practices for Component Development
AEM Best Practices for Component DevelopmentAEM Best Practices for Component Development
AEM Best Practices for Component Development
 
Angular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdfAngular Interview Questions-PDF.pdf
Angular Interview Questions-PDF.pdf
 
Introduction To Single Page Application
Introduction To Single Page ApplicationIntroduction To Single Page Application
Introduction To Single Page Application
 
AEM Sightly Template Language
AEM Sightly Template LanguageAEM Sightly Template Language
AEM Sightly Template Language
 
HTL(Sightly) - All you need to know
HTL(Sightly) - All you need to knowHTL(Sightly) - All you need to know
HTL(Sightly) - All you need to know
 
Xke spring boot
Xke spring bootXke spring boot
Xke spring boot
 
Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.Introduction into ES6 JavaScript.
Introduction into ES6 JavaScript.
 
TF에서 팀 빌딩까지 9개월의 기록 : 성장하는 조직을 만드는 여정
TF에서 팀 빌딩까지 9개월의 기록 : 성장하는 조직을 만드는 여정TF에서 팀 빌딩까지 9개월의 기록 : 성장하는 조직을 만드는 여정
TF에서 팀 빌딩까지 9개월의 기록 : 성장하는 조직을 만드는 여정
 
Saving Time By Testing With Jest
Saving Time By Testing With JestSaving Time By Testing With Jest
Saving Time By Testing With Jest
 
Spring Boot & Actuators
Spring Boot & ActuatorsSpring Boot & Actuators
Spring Boot & Actuators
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 

En vedette

Service Workers for Performance
Service Workers for PerformanceService Workers for Performance
Service Workers for PerformancePatrick Meenan
 
"Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native ""Service Worker: Let Your Web App Feel Like a Native "
"Service Worker: Let Your Web App Feel Like a Native "FDConf
 
Service workers your applications never felt so good
Service workers   your applications never felt so goodService workers   your applications never felt so good
Service workers your applications never felt so goodChris Love
 
Service workers - Velocity 2016 Training
Service workers - Velocity 2016 TrainingService workers - Velocity 2016 Training
Service workers - Velocity 2016 TrainingPatrick Meenan
 
Scalable Angular 2 Application Architecture
Scalable Angular 2 Application ArchitectureScalable Angular 2 Application Architecture
Scalable Angular 2 Application ArchitectureFDConf
 
Machine Learning RUM - Velocity 2016
Machine Learning RUM - Velocity 2016Machine Learning RUM - Velocity 2016
Machine Learning RUM - Velocity 2016Patrick Meenan
 
TLS - 2016 Velocity Training
TLS - 2016 Velocity TrainingTLS - 2016 Velocity Training
TLS - 2016 Velocity TrainingPatrick Meenan
 
Progressive Web Apps [pt_BR]
Progressive Web Apps [pt_BR]Progressive Web Apps [pt_BR]
Progressive Web Apps [pt_BR]Evandro Santos
 
Introduction to Progressive Web Apps, Google Developer Summit, Seoul - South ...
Introduction to Progressive Web Apps, Google Developer Summit, Seoul - South ...Introduction to Progressive Web Apps, Google Developer Summit, Seoul - South ...
Introduction to Progressive Web Apps, Google Developer Summit, Seoul - South ...Robert Nyman
 
Introduction to Progressive web app (PWA)
Introduction to Progressive web app (PWA)Introduction to Progressive web app (PWA)
Introduction to Progressive web app (PWA)Zhentian Wan
 
Scaling Front-End Performance - Velocity 2016
Scaling Front-End Performance - Velocity 2016Scaling Front-End Performance - Velocity 2016
Scaling Front-End Performance - Velocity 2016Patrick Meenan
 
Progressive Web App
Progressive Web AppProgressive Web App
Progressive Web AppSubodh Garg
 

En vedette (12)

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

Similaire à Service workers

[1C1]Service Workers
[1C1]Service Workers[1C1]Service Workers
[1C1]Service WorkersNAVER D2
 
Service Worker - Reliability bits
Service Worker - Reliability bitsService Worker - Reliability bits
Service Worker - Reliability bitsjungkees
 
PWA Roadshow Korea - Service Worker
PWA Roadshow Korea - Service WorkerPWA Roadshow Korea - Service Worker
PWA Roadshow Korea - Service Workerjungkees
 
ServiceWorker: New game changer is coming!
ServiceWorker: New game changer is coming!ServiceWorker: New game changer is coming!
ServiceWorker: New game changer is coming!Chang W. Doh
 
Offline First with Service Worker
Offline First with Service WorkerOffline First with Service Worker
Offline First with Service WorkerMuhammad Samu
 
JQuery UK February 2015: Service Workers On Vacay
JQuery UK February 2015: Service Workers On VacayJQuery UK February 2015: Service Workers On Vacay
JQuery UK February 2015: Service Workers On VacayNatasha Rooney
 
JQuery UK Service Workers Talk
JQuery UK Service Workers TalkJQuery UK Service Workers Talk
JQuery UK Service Workers TalkNatasha Rooney
 
Service workers and the role they play in modern day web apps
Service workers and the role they play in modern day web appsService workers and the role they play in modern day web apps
Service workers and the role they play in modern day web appsMukul Jain
 
Progressive Web Apps 101
Progressive Web Apps 101Progressive Web Apps 101
Progressive Web Apps 101Muhammad Samu
 
PWA 與 Service Worker
PWA 與 Service WorkerPWA 與 Service Worker
PWA 與 Service WorkerAnna Su
 
Service worker: discover the next web game changer
Service worker: discover the next web game changerService worker: discover the next web game changer
Service worker: discover the next web game changerSandro Paganotti
 
Building Offline Ready and Installable Web App
Building Offline Ready and Installable Web AppBuilding Offline Ready and Installable Web App
Building Offline Ready and Installable Web AppMuhammad Samu
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Building Progressive Web Apps for Windows devices
Building Progressive Web Apps for Windows devicesBuilding Progressive Web Apps for Windows devices
Building Progressive Web Apps for Windows devicesWindows Developer
 
HTML5: huh, what is it good for?
HTML5: huh, what is it good for?HTML5: huh, what is it good for?
HTML5: huh, what is it good for?Remy Sharp
 
Building with Firebase
Building with FirebaseBuilding with Firebase
Building with FirebaseMike Fowler
 

Similaire à Service workers (20)

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

Plus de jungkees

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

Plus de jungkees (7)

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

Dernier

Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
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
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
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
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
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
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
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
 
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
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
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
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 

Dernier (20)

Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
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
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
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
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
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
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
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)
 
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...
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
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
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 

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