SlideShare a Scribd company logo
Introduction to
Service Workers
What is a Service Worker?
● Javascript Worker
○ run in background
○ no DOM access
○ only localhost or HTTPS
● Programmable network proxy
○ control how network requests are handled
● Background Sync
● Push notification
Support table
How to install Service Worker
ServiceWorkerContainer.register(scriptUrl[, options]):Promise
● scriptUrl is the path to service worker script
● options: an object containing registration options
○ scope: what range of URLs a service worker can control
The default scope is the scriptUrl directory.
E.g. /example/sw.js -> /example/*
How to install Service Worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/sw.js')
// Registration was successful
.then(registration => console.log(
'ServiceWorker registration successful with scope: ',
registration.scope
))
// registration failed :(
.catch(err => console.log(
'ServiceWorker registration failed: ',
err
));
}
Inside the Service Worker
importScripts('./myLib.js');
self.addEventListener('install', () => console.log('installed'));
self.addEventListener('activate', () => console.log('activate'));
self.addEventListener('fetch', () => console.log('fetch'));
self.addEventListener('sync', () => console.log('sync'));
self.addEventListener('push', () => console.log('push'));
Inside the Service Worker: Events
● Install: it’s called once per SW. Through this event you can cache everything
you need before being able to control clients using waitUntil() method.
● Activate: after installation. It is for cleanup of resources used in previous
versions of a Service worker script.
● Fetch: when SW is ready and the controlled client is fetching some
resources.
Inside the Service Worker: Cache
The caches object is available in sw scope as in window. It manages multiple
named cache.
● caches.open(cacheName):Promise(cache)
● caches.keys(): Array of cache names
● caches.has(cacheName)
● caches.delete(cacheName)
Ref: https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage
Inside the Service Worker: Cache
The cache object provides a storage mechanism for Request / Response object
pairs that are cached.
● cache.put(request, response):Promise
● cache.add(request):Promise
● cache.addAll([request]):Promise
● cache.delete(request):Promise
● cache.match(request):Promise<Response>
Ref: https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage
Inside the Service Worker: SW Event Install
self.addEventListener('install', event => {
console.log('V2 installing…');
// cache a horse SVG into a new cache, static-v2
event.waitUntil(
caches.open('static-v2').then(cache => cache.add('/horse.svg'))
);
});
Inside the Service Worker: SW Event Activate
self.addEventListener('activate', event => {
// delete any caches that aren't in expectedCaches which will get rid of static-v1
event.waitUntil(
caches.keys().then(keys => Promise.all(
keys.map(key => {
if (!expectedCaches.includes(key))
return caches.delete(key);
})
)).then(() => {
console.log('V2 now ready to handle fetches!');
})
);
});
Inside the Service Worker: SW Event Fetch
self.addEventListener('fetch', function (event) {
event.respondWith(
caches.match(event.request)
);
});
Offline Strategies: utilities
function getFromCache(request) {
return caches.open('v1')
.then(cache => cache.match(request));
}
function putInCache(request, response) {
return caches.open('v1')
.then(() => cache.put(request, response.clone()));
}
function fetchAndCache(request) {
return fetch(request).then(response => {
response.ok && putInCache(request, response);
return response;
}
}
Offline Strategies: only from cache
self.addEventListener('install', event =>
event.waitUntil(
caches.open('v1').then(cache => cache.add('/index.html'))
);
);
self.addEventListener('fetch', event =>
event.respondWith(
getFromCache(event.request)
);
);
Offline Strategies: cache, then network
self.addEventListener('fetch', event =>
event.respondWith(
caches.match(event.request)
.then(resp => resp || fetchAndCache(event.request));
);
);
Offline Strategies: network, then cache
self.addEventListener('fetch', event =>
event.respondWith(
fetchAndCache(event.request)
.then(
resp => resp.ok ? resp : getFromCache(event.request),
getFromCache(event.request)
)
);
);
Offline Strategies: cache, then refresh from network
self.addEventListener('fetch', event => {
event.respondWith(getFromCache(event.request));
event.waitUntil(
fetchAndCache(event.request).then(refresh);
)
});
function refresh(response) {
return self.clients.matchAll().then(clients =>
clients.forEach(client =>
client.postMessage(JSON.stringify({
type: 'refresh',
url: response.url,
}));
)
);
}
Demo time!
Background Sync
● sync event fired in SW in two case:
○ when you register an event if you’re online
registration.sync.register('send-outbox')
○ otherwise it’s queued if you’re offline and fired once online
● The queued events will be fired in SW also if there is no controlled window
● Period Sync will be available soon:
registration.periodicSync.register({
tag: 'get-latest-news', // default: ''
minPeriod: 12 * 60 * 60 * 1000, // default: 0
powerState: 'avoid-draining', // default: 'auto'
networkState: 'avoid-cellular' // default: 'online'
});
Support table
Demo time!
Push Notification
● Server to client communication
● Google Cloud Messaging
● It works without any controlled window
const applicationServerKey = urlB64ToUint8Array(serverPublicKey);
registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
});
Push Notification
// main.js
const applicationServerKey = urlB64ToUint8Array(serverPublicKey);
registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
});
// sw.js
self.addEventListener('push', function(event) {
console.log('[Service Worker] Push Received.');
console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);
const title = 'Push Notification';
const options = {
body: 'Hello world!', icon: 'images/icon.png', badge: 'images/badge.png'
};
event.waitUntil(self.registration.showNotification(title, options));
});
Support table
Useful resources
● https://developers.google.com/web/fundamentals/primers/service-workers/
● https://serviceworke.rs/
● https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
● https://github.com/goldhand/sw-precache-webpack-plugin
Thank you!

More Related Content

PDF
Workboxで始める Service Worker
PDF
Arduino & node.js
PPTX
Deceptive simplicity of async and await
PPTX
Bucks County Tech Meetup: node.js introduction
PPTX
Asynchronous programming
PPTX
No More Deadlocks; Asynchronous Programming in .NET
PPTX
Correcting Common Async/Await Mistakes in .NET
PDF
Why Redux-Observable?
Workboxで始める Service Worker
Arduino & node.js
Deceptive simplicity of async and await
Bucks County Tech Meetup: node.js introduction
Asynchronous programming
No More Deadlocks; Asynchronous Programming in .NET
Correcting Common Async/Await Mistakes in .NET
Why Redux-Observable?

What's hot (20)

PPTX
Avoiding callback hell in Node js using promises
PPTX
Correcting Common .NET Async/Await Mistakes
PPT
Expert JavaScript tricks of the masters
PDF
You will learn RxJS in 2017
PDF
Asynchronní programování
PPTX
How NOT to write in Node.js
ODP
Building serverless application on the Apache Openwhisk platform
PDF
Universal JavaScript
PDF
#Gophercon Talk by Smita Vijayakumar - Go's Context Library
PDF
RxJS - 封裝程式的藝術
PPTX
Rxjs swetugg
PDF
Understanding Asynchronous JavaScript
PPTX
Rxjs ngvikings
PDF
Oop assignment 02
PDF
如何「畫圖」寫測試 - RxJS Marble Test
PDF
Angular and The Case for RxJS
PPTX
Async best practices DotNet Conference 2016
PPTX
Async Best Practices
PPTX
Understanding reactive programming with microsoft reactive extensions
PDF
Mirage For Beginners
Avoiding callback hell in Node js using promises
Correcting Common .NET Async/Await Mistakes
Expert JavaScript tricks of the masters
You will learn RxJS in 2017
Asynchronní programování
How NOT to write in Node.js
Building serverless application on the Apache Openwhisk platform
Universal JavaScript
#Gophercon Talk by Smita Vijayakumar - Go's Context Library
RxJS - 封裝程式的藝術
Rxjs swetugg
Understanding Asynchronous JavaScript
Rxjs ngvikings
Oop assignment 02
如何「畫圖」寫測試 - RxJS Marble Test
Angular and The Case for RxJS
Async best practices DotNet Conference 2016
Async Best Practices
Understanding reactive programming with microsoft reactive extensions
Mirage For Beginners
Ad

Similar to Introduction to Service Workers | Matteo Manchi (20)

PPTX
Academy PRO: Push notifications. Denis Beketsky
PDF
Service Worker - Reliability bits
PDF
PWA 與 Service Worker
PDF
Service workers
PDF
Service Worker Presentation
PDF
[1C1]Service Workers
PDF
JSChannel 2017 - Service Workers and the Role they Play in modern day web-apps
PDF
Service worker: discover the next web game changer
PDF
New improvements for web developers - frontend.fi, Helsinki
PDF
Service workers
PDF
"Service Worker: Let Your Web App Feel Like a Native "
PDF
ServiceWorker: Exploring the Core of the Progressive Web App-Bagus Aji Santos...
KEY
How and why i roll my own node.js framework
PDF
Scheduling tasks the human way - Brad Wood - ITB2021
PDF
Future Decoded - Node.js per sviluppatori .NET
PPTX
Service workers and the role they play in modern day web apps
PDF
Bonnes pratiques de développement avec Node js
PDF
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
PPTX
[NDC 2019] Enterprise-Grade Serverless
PPTX
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
Academy PRO: Push notifications. Denis Beketsky
Service Worker - Reliability bits
PWA 與 Service Worker
Service workers
Service Worker Presentation
[1C1]Service Workers
JSChannel 2017 - Service Workers and the Role they Play in modern day web-apps
Service worker: discover the next web game changer
New improvements for web developers - frontend.fi, Helsinki
Service workers
"Service Worker: Let Your Web App Feel Like a Native "
ServiceWorker: Exploring the Core of the Progressive Web App-Bagus Aji Santos...
How and why i roll my own node.js framework
Scheduling tasks the human way - Brad Wood - ITB2021
Future Decoded - Node.js per sviluppatori .NET
Service workers and the role they play in modern day web apps
Bonnes pratiques de développement avec Node js
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
Ad

More from Codemotion (20)

PDF
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
PDF
Pompili - From hero to_zero: The FatalNoise neverending story
PPTX
Pastore - Commodore 65 - La storia
PPTX
Pennisi - Essere Richard Altwasser
PPTX
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
PPTX
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
PPTX
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
PPTX
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
PDF
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
PDF
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
PDF
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
PDF
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
PDF
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
PDF
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
PPTX
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
PPTX
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
PDF
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
PDF
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
PDF
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
PDF
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Pompili - From hero to_zero: The FatalNoise neverending story
Pastore - Commodore 65 - La storia
Pennisi - Essere Richard Altwasser
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019

Recently uploaded (20)

PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPT
Teaching material agriculture food technology
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
KodekX | Application Modernization Development
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
cuic standard and advanced reporting.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Digital-Transformation-Roadmap-for-Companies.pptx
The AUB Centre for AI in Media Proposal.docx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
20250228 LYD VKU AI Blended-Learning.pptx
Network Security Unit 5.pdf for BCA BBA.
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Understanding_Digital_Forensics_Presentation.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
Unlocking AI with Model Context Protocol (MCP)
Encapsulation_ Review paper, used for researhc scholars
Reach Out and Touch Someone: Haptics and Empathic Computing
Teaching material agriculture food technology
MYSQL Presentation for SQL database connectivity
Review of recent advances in non-invasive hemoglobin estimation
Programs and apps: productivity, graphics, security and other tools
KodekX | Application Modernization Development
Chapter 3 Spatial Domain Image Processing.pdf
cuic standard and advanced reporting.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx

Introduction to Service Workers | Matteo Manchi

  • 2. What is a Service Worker? ● Javascript Worker ○ run in background ○ no DOM access ○ only localhost or HTTPS ● Programmable network proxy ○ control how network requests are handled ● Background Sync ● Push notification
  • 4. How to install Service Worker ServiceWorkerContainer.register(scriptUrl[, options]):Promise ● scriptUrl is the path to service worker script ● options: an object containing registration options ○ scope: what range of URLs a service worker can control The default scope is the scriptUrl directory. E.g. /example/sw.js -> /example/*
  • 5. How to install Service Worker if ('serviceWorker' in navigator) { navigator.serviceWorker .register('/sw.js') // Registration was successful .then(registration => console.log( 'ServiceWorker registration successful with scope: ', registration.scope )) // registration failed :( .catch(err => console.log( 'ServiceWorker registration failed: ', err )); }
  • 6. Inside the Service Worker importScripts('./myLib.js'); self.addEventListener('install', () => console.log('installed')); self.addEventListener('activate', () => console.log('activate')); self.addEventListener('fetch', () => console.log('fetch')); self.addEventListener('sync', () => console.log('sync')); self.addEventListener('push', () => console.log('push'));
  • 7. Inside the Service Worker: Events ● Install: it’s called once per SW. Through this event you can cache everything you need before being able to control clients using waitUntil() method. ● Activate: after installation. It is for cleanup of resources used in previous versions of a Service worker script. ● Fetch: when SW is ready and the controlled client is fetching some resources.
  • 8. Inside the Service Worker: Cache The caches object is available in sw scope as in window. It manages multiple named cache. ● caches.open(cacheName):Promise(cache) ● caches.keys(): Array of cache names ● caches.has(cacheName) ● caches.delete(cacheName) Ref: https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage
  • 9. Inside the Service Worker: Cache The cache object provides a storage mechanism for Request / Response object pairs that are cached. ● cache.put(request, response):Promise ● cache.add(request):Promise ● cache.addAll([request]):Promise ● cache.delete(request):Promise ● cache.match(request):Promise<Response> Ref: https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage
  • 10. Inside the Service Worker: SW Event Install self.addEventListener('install', event => { console.log('V2 installing…'); // cache a horse SVG into a new cache, static-v2 event.waitUntil( caches.open('static-v2').then(cache => cache.add('/horse.svg')) ); });
  • 11. Inside the Service Worker: SW Event Activate self.addEventListener('activate', event => { // delete any caches that aren't in expectedCaches which will get rid of static-v1 event.waitUntil( caches.keys().then(keys => Promise.all( keys.map(key => { if (!expectedCaches.includes(key)) return caches.delete(key); }) )).then(() => { console.log('V2 now ready to handle fetches!'); }) ); });
  • 12. Inside the Service Worker: SW Event Fetch self.addEventListener('fetch', function (event) { event.respondWith( caches.match(event.request) ); });
  • 13. Offline Strategies: utilities function getFromCache(request) { return caches.open('v1') .then(cache => cache.match(request)); } function putInCache(request, response) { return caches.open('v1') .then(() => cache.put(request, response.clone())); } function fetchAndCache(request) { return fetch(request).then(response => { response.ok && putInCache(request, response); return response; } }
  • 14. Offline Strategies: only from cache self.addEventListener('install', event => event.waitUntil( caches.open('v1').then(cache => cache.add('/index.html')) ); ); self.addEventListener('fetch', event => event.respondWith( getFromCache(event.request) ); );
  • 15. Offline Strategies: cache, then network self.addEventListener('fetch', event => event.respondWith( caches.match(event.request) .then(resp => resp || fetchAndCache(event.request)); ); );
  • 16. Offline Strategies: network, then cache self.addEventListener('fetch', event => event.respondWith( fetchAndCache(event.request) .then( resp => resp.ok ? resp : getFromCache(event.request), getFromCache(event.request) ) ); );
  • 17. Offline Strategies: cache, then refresh from network self.addEventListener('fetch', event => { event.respondWith(getFromCache(event.request)); event.waitUntil( fetchAndCache(event.request).then(refresh); ) }); function refresh(response) { return self.clients.matchAll().then(clients => clients.forEach(client => client.postMessage(JSON.stringify({ type: 'refresh', url: response.url, })); ) ); }
  • 19. Background Sync ● sync event fired in SW in two case: ○ when you register an event if you’re online registration.sync.register('send-outbox') ○ otherwise it’s queued if you’re offline and fired once online ● The queued events will be fired in SW also if there is no controlled window ● Period Sync will be available soon: registration.periodicSync.register({ tag: 'get-latest-news', // default: '' minPeriod: 12 * 60 * 60 * 1000, // default: 0 powerState: 'avoid-draining', // default: 'auto' networkState: 'avoid-cellular' // default: 'online' });
  • 22. Push Notification ● Server to client communication ● Google Cloud Messaging ● It works without any controlled window const applicationServerKey = urlB64ToUint8Array(serverPublicKey); registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: applicationServerKey });
  • 23. Push Notification // main.js const applicationServerKey = urlB64ToUint8Array(serverPublicKey); registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: applicationServerKey }); // sw.js self.addEventListener('push', function(event) { console.log('[Service Worker] Push Received.'); console.log(`[Service Worker] Push had this data: "${event.data.text()}"`); const title = 'Push Notification'; const options = { body: 'Hello world!', icon: 'images/icon.png', badge: 'images/badge.png' }; event.waitUntil(self.registration.showNotification(title, options)); });
  • 25. Useful resources ● https://developers.google.com/web/fundamentals/primers/service-workers/ ● https://serviceworke.rs/ ● https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API ● https://github.com/goldhand/sw-precache-webpack-plugin