SlideShare a Scribd company logo
Service Worker
Reliability bits
Jungkee Song
Senior engineer at Samsung
Web standards author
Chromium contributor
Email: jungkee.song@samsung.com
GitHub: @jungkees
Service Worker - Reliability bits
Samsung Internet
4.0 shipped SW!
Service Worker
Reliability
Progressive Web Apps
Service Worker - Reliability bits
Progressive Web Apps
• Reliability
− Fast loading, works on flaky networks
• First-class
− Do what native does, background
• Engaging
− Home screen access, push notification
Progressive Web Apps
Service Worker
What to solve
Problems
Problems
Not only
But ..
Problems
• Background service
− Was not possible without a page
The Total Game Changer!
https://youtu.be/QiXLaisCq10
Udacity Offline-First Web Applications Trailer
Service Worker
Concepts
What to solve
Your programable proxy
Page
Browser
Service Worker
Cache
NetloaderandHTTPcache
Service Worker
Concept
Script runs in the background
A type of web worker
var worker = new Worker(‘dedicated_worker.js');
var worker = new SharedWorker(‘shared_worker.js’);
navigator.serviceWorker.register(“/service_worker.js");
Service Worker
Event-driven
Responds to events
fetch event
Navigation/Resource request
onfetch
Page
SW
Cache
Attempt to match cache
Matched Response
Respond to client
Page Page
Event-based worker
Service Worker
Power matters
Intentionally short lifetime
Bound to page
Page
Worker
new Worker(‘job.js’)
Run job.js
t
Dedicated worker
* Lifetime is bound to the page unless .terminate is called.
Event-driven
Page
SW
fetch event
e.g.<img src=‘pic.png’>
Run sw.js
Browser internal
t
Service worker
Term
inate
Start
onfetch
e.waitUntil
push eventStart
Term
inate
onpush
e.waitUntil
Registration and SW
registration active worker waiting worker installing worker
ServiceWorkerRegistration
active
active
installing
Persistent
Client scope
fetch install
registration.active
Browser
Internals
Script
Surface
registration.active
registration.installing
ServiceWorkerRegistration
ServiceWorker
ServiceWorker
ServiceWorker
Page Page
Service Worker
Make it secure
HTTPS
HTTPS
• SW allows powerful stuffs
− Intercept requests and fabricate your
own responses
• Need to guarantee it has not been tempered
during its own fetch
− localhost is allowed during development
− HTTPS setup is needed to deploy
Service Worker
Get it ready
Install and Update
and every navigation and functional event
Install
var navigator.serviceWorker;
sw.register(scriptURL, { scope: scopeURL });
Pre-cache resources
oninstall = e => { /* pre-cache here */ };
Handle fetch event
onfetch = e => { /* respond with magic */ };
Manage Cache
onactivate = e => { /* Deleting cache is on you */ };
Update
registration.update();
“/assets/v1” /assets/v1/serviceworker.js
[ Registration map ]
Scope Script URL
Register
From page
// scope defaults to "/"
var sw = navigator.serviceWorker;
sw.register("/assets/v1/serviceworker.js")
.then(reg => {
console.log("success!");
reg.installing.postMessage("Howdy from your installing page.");
})
.catch(e => {
console.error("Installing the worker failed!:", e);
});
“/bar” /bar/sw1.js
[ Registration map ]
Scope Script URL
“/foo” /foo/sw.js
Register – Multiple registrations
From page
var sw = navigator.serviceWorker;
① sw.register('/bar/sw1.js', { scope: '/bar' });
② sw.register('/foo/sw.js', { scope: '/foo' });
③ sw.register('/bar/sw2.js', { scope: '/bar' } );
“/bar” /bar/sw2.js
onactivate
SW
oninstall
onfetch
Browser internals
oninstall = e => {
// pre-cache, etc.
};
onactivate = e => {
// upgrade Cache, etc.
};
onfetch = e => {
// Not yet ready
};
Fetched sw script
Fetch sw script
Update① ③ Install
④ Activate
onfetch
onfetch = e => {
// Not yet ready
};
Install process triggered by register
Evaluate②
installinginstalledactivated
Service Worker
How interception work
Client matching
&
Subresource request
onfetch
sw.js
Cache
Attempt to match cache
Matched response
Respond to client
“/” /sw.js
[ Registration map ]
Scope Script URL
“/foo” /foo/sw.js
Page
Navigate https://example.com/index.html
fetch event
Scope matching
Run SW
Client matching (navigation)
onfetch
sw.js
Cache
Attempt to match cache
Matched response
Respond to client
“/” /sw.js
[ Registration map ]
Scope Script URL
“/img” /img/sw.js
Page
Fetch “https://example.com/img/flower.png
fetch event
Control
Run SW
Subresource request
Service Worker
How to handle fetch
Patterns
Cache of static resources in oninstall
https://jakearchibald.com/2014/offline-cookbook/#on-install-as-a-dependency
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open('mysite-static-v3').then(function(cache) {
return cache.addAll([
'/css/whatever-v3.css',
'/css/imgs/sprites-v6.png',
'/css/fonts/whatever-v8.woff',
'/js/all-min-v4.js'
// etc
]);
})
);
});
Cache on user demand
document.querySelector('.cache-article').addEventListener('click', function(event) {
event.preventDefault();
var id = this.dataset.articleId;
caches.open('mysite-article-' + id).then(function(cache) {
fetch('/get-article-urls?id=' + id).then(function(response) {
// /get-article-urls returns a JSON-encoded array of
// resource URLs that a given article depends on
return response.json();
}).then(function(urls) {
cache.addAll(urls);
});
});
});
https://jakearchibald.com/2014/offline-cookbook/#on-user-interaction
Cache of dynamic resource
https://jakearchibald.com/2014/offline-cookbook/#on-network-response
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.open('mysite-dynamic').then(function(cache) {
return cache.match(event.request).then(function (response) {
return response || fetch(event.request).then(function(response) {
cache.put(event.request, response.clone());
return response;
});
});
})
);
});
Cache migration in onactivate
https://jakearchibald.com/2014/offline-cookbook/#on-activate
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
// Return true if you want to remove this cache,
// but remember that caches are shared across
// the whole origin
}).map(function(cacheName) {
return caches.delete(cacheName);
})
);
})
);
});
onpush
https://jakearchibald.com/2014/offline-cookbook/#on-push-message
self.addEventListener('push', function(event) {
if (event.data.text() == 'new-email') {
event.waitUntil(
caches.open('mysite-dynamic').then(function(cache) {
return fetch('/inbox.json').then(function(response) {
cache.put('/inbox.json', response.clone());
return response.json();
});
}).then(function(emails) {
registration.showNotification("New email", {
body: "From " + emails[0].from.name
tag: "new-email"
});
})
);
}
});
self.addEventListener('notificationclick', function(event) {
if (event.notification.tag == 'new-email') {
// Assume that all of the resources needed to render
// /inbox/ have previously been cached, e.g. as part
// of the install handler.
clients.openWindow(‘/inbox/');
}
});
Offline Cookbook
https://jakearchibald.com/2014/offline-cookbook/
Application Shell
• Minimal HTML, CSS, and JavaScript powering UI
• Should
− Load fast
− Be cached
− Dynamically display content
https://developers.google.com/web/updates/2015/11/app-shell
Service Worker
Yeah, it works!
Demo
http://stories.flipkart.com/introducing-flipkart-lite/
Service Worker
Yeah, we want more!
Status
Standards
Implementation
4th WD in June 2105
Plan a CR in the 3Q of this year
4.0 40+ 44 32+
Service Worker
And.. Your turn!
In the wild
https://pwa.rocks/
Service Worker
V2 stuffs
Future
V2 features
• Foreign fetch
• Cache transaction
• Declarative register

More Related Content

PDF
Service workers
PDF
PWA 與 Service Worker
PDF
Service workers
PDF
[1C1]Service Workers
PDF
Service worker API
PDF
Instant and offline apps with Service Worker
PDF
Service Worker Presentation
PPTX
Real World Lessons in Progressive Web Application & Service Worker Caching
Service workers
PWA 與 Service Worker
Service workers
[1C1]Service Workers
Service worker API
Instant and offline apps with Service Worker
Service Worker Presentation
Real World Lessons in Progressive Web Application & Service Worker Caching

What's hot (20)

PDF
Service worker - Offline Web
PDF
PWA 應用 - 實現網站離線瀏覽
PDF
JQuery UK Service Workers Talk
PDF
JQuery UK February 2015: Service Workers On Vacay
PDF
"Service Worker: Let Your Web App Feel Like a Native "
PDF
Service worker: discover the next web game changer
PDF
PWA Roadshow Seoul - HTTPS
PPTX
Service workers and the role they play in modern day web apps
PDF
Building a js widget
PPTX
Building Offline Ready and Installable Web App
PDF
PWA Roadshow Korea - Service Worker
PDF
JavaScript APIs - The Web is the Platform
PPTX
Testing frontends with nightwatch & saucelabs
PDF
Drupal point of vue
PDF
React & The Art of Managing Complexity
PDF
WordPress 2017 with VueJS and GraphQL
PPTX
Automated release management with team city & octopusdeploy - NDC 2013
PPTX
Nodejs.meetup
PDF
JS Chicago Meetup 2/23/16 - Redux & Routes
PDF
Chrome enchanted 2015
Service worker - Offline Web
PWA 應用 - 實現網站離線瀏覽
JQuery UK Service Workers Talk
JQuery UK February 2015: Service Workers On Vacay
"Service Worker: Let Your Web App Feel Like a Native "
Service worker: discover the next web game changer
PWA Roadshow Seoul - HTTPS
Service workers and the role they play in modern day web apps
Building a js widget
Building Offline Ready and Installable Web App
PWA Roadshow Korea - Service Worker
JavaScript APIs - The Web is the Platform
Testing frontends with nightwatch & saucelabs
Drupal point of vue
React & The Art of Managing Complexity
WordPress 2017 with VueJS and GraphQL
Automated release management with team city & octopusdeploy - NDC 2013
Nodejs.meetup
JS Chicago Meetup 2/23/16 - Redux & Routes
Chrome enchanted 2015
Ad

Similar to Service Worker - Reliability bits (20)

PPTX
Offline First with Service Worker
PPTX
Building Progressive Web Apps for Windows devices
KEY
Writing robust Node.js applications
PDF
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
PDF
The Open Web and what it means
PDF
HTML5: huh, what is it good for?
PDF
Bringing the open web and APIs to mobile devices with Firefox OS - Whisky W...
PPTX
Progressive Web Apps 101
PDF
Web APIs & Apps - Mozilla
PDF
Building websites with Node.ACS
PDF
Building websites with Node.ACS
KEY
Express Presentation
PDF
Always on! Or not?
PDF
Serverless Java on Kubernetes
PDF
RESS – Responsive Webdesign and Server Side Components
PPTX
Progressive What Apps?
PDF
Building and deploying React applications
PDF
HTML5 tutorial: canvas, offfline & sockets
PDF
Progressive Web Apps
PDF
Workboxで始める Service Worker
Offline First with Service Worker
Building Progressive Web Apps for Windows devices
Writing robust Node.js applications
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
The Open Web and what it means
HTML5: huh, what is it good for?
Bringing the open web and APIs to mobile devices with Firefox OS - Whisky W...
Progressive Web Apps 101
Web APIs & Apps - Mozilla
Building websites with Node.ACS
Building websites with Node.ACS
Express Presentation
Always on! Or not?
Serverless Java on Kubernetes
RESS – Responsive Webdesign and Server Side Components
Progressive What Apps?
Building and deploying React applications
HTML5 tutorial: canvas, offfline & sockets
Progressive Web Apps
Workboxで始める Service Worker
Ad

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
Slides PPTX World Game (s) Eco Economic Epochs.pptx
PPT
Design_with_Watersergyerge45hrbgre4top (1).ppt
PPTX
introduction about ICD -10 & ICD-11 ppt.pptx
PPT
tcp ip networks nd ip layering assotred slides
PPTX
Module 1 - Cyber Law and Ethics 101.pptx
PPTX
artificial intelligence overview of it and more
PDF
APNIC Update, presented at PHNOG 2025 by Shane Hermoso
PDF
The New Creative Director: How AI Tools for Social Media Content Creation Are...
PPTX
June-4-Sermon-Powerpoint.pptx USE THIS FOR YOUR MOTIVATION
PPTX
Job_Card_System_Styled_lorem_ipsum_.pptx
PPTX
CHE NAA, , b,mn,mblblblbljb jb jlb ,j , ,C PPT.pptx
PDF
Best Practices for Testing and Debugging Shopify Third-Party API Integrations...
PPTX
Introduction to Information and Communication Technology
PPTX
Introuction about ICD -10 and ICD-11 PPT.pptx
PPTX
Power Point - Lesson 3_2.pptx grad school presentation
PDF
SASE Traffic Flow - ZTNA Connector-1.pdf
PPTX
INTERNET------BASICS-------UPDATED PPT PRESENTATION
PDF
Tenda Login Guide: Access Your Router in 5 Easy Steps
PDF
💰 𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓 💰
PDF
How to Ensure Data Integrity During Shopify Migration_ Best Practices for Sec...
Slides PPTX World Game (s) Eco Economic Epochs.pptx
Design_with_Watersergyerge45hrbgre4top (1).ppt
introduction about ICD -10 & ICD-11 ppt.pptx
tcp ip networks nd ip layering assotred slides
Module 1 - Cyber Law and Ethics 101.pptx
artificial intelligence overview of it and more
APNIC Update, presented at PHNOG 2025 by Shane Hermoso
The New Creative Director: How AI Tools for Social Media Content Creation Are...
June-4-Sermon-Powerpoint.pptx USE THIS FOR YOUR MOTIVATION
Job_Card_System_Styled_lorem_ipsum_.pptx
CHE NAA, , b,mn,mblblblbljb jb jlb ,j , ,C PPT.pptx
Best Practices for Testing and Debugging Shopify Third-Party API Integrations...
Introduction to Information and Communication Technology
Introuction about ICD -10 and ICD-11 PPT.pptx
Power Point - Lesson 3_2.pptx grad school presentation
SASE Traffic Flow - ZTNA Connector-1.pdf
INTERNET------BASICS-------UPDATED PPT PRESENTATION
Tenda Login Guide: Access Your Router in 5 Easy Steps
💰 𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓 💰
How to Ensure Data Integrity During Shopify Migration_ Best Practices for Sec...

Service Worker - Reliability bits