SlideShare a Scribd company logo
1 of 28
Download to read offline
Service Worker
Overview
● What is a Service Worker?
● What existed before the Service Worker?
● Lifecycle of a Service Worker
● Use cases
● A fair assessment (a.k.a. the bad)
What is a service worker?
A service worker is a script that is run
by your browser in the background,
separate from a web page
● It's a JavaScript Worker, so it can't access the DOM
directly
● Service worker is a programmable network proxy,
allowing you to control how network requests from your
page are handled.
● It will be terminated when not in use, and restarted
when it's next needed
● Service workers are asynchronous and make extensive
use of promises
● Service workers require content to be served via https
What existed before the Service Worker?
AppCache
CACHE MANIFEST
assets/6/script/mainmin.js
assets/6/style/mainmin.css
assets/6/style/fonts/pro.ttf
assets/6/style/imgs/sprites1.png
<html manifest="offline.appcache">
Using the Service Worker
Service Worker Lifecycle
1. The service worker URL is fetched
and registered
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/trained-to-thrill/sw.js')
.then(function(reg) {
console.log('success!', reg);
}, function(err) {
console.log('error!', err);
});
}
2. If successful, the service worker is
executed in a ServiceWorkerGlobalScope;
this is basically a special kind of worker
context, running off the main script execution
thread, with no DOM access.
3. The service worker is now ready to
process events.
4. Installation of the worker is
attempted when service worker-
controlled pages are accessed
subsequently. An Install event is
always the first one sent to a service
worker
5. Same procedure as installing a
native app — making everything
available for use offline.
6. When the oninstall handler completes,
the service worker is considered installed.
self.oninstall = function(event) {
event.waitUntil(
caches.open('trains-static-v14').then(function(cache) {
return cache.addAll([
'/trained-to-thrill/',
'/trained-to-thrill/static/css/all.css',
'/trained-to-thrill/static/js/page.js',
'/trained-to-thrill/static/imgs/logo.svg',
'/trained-to-thrill/static/imgs/icon.png'
]);
})
);
};
7. When the service worker is installed, it
then receives an activate event. The
primary use of onactivate is for cleanup of
resources used in previous versions of a
Service Worker script.
self.onactivate = function(event) {
// remove caches beginning "trains-" that aren't in
// expectedCaches
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (!/^trains-/.test(cacheName)) {
return;
}
if (expectedCaches.indexOf(cacheName) == -1) {
return caches.delete(cacheName);
}}));}));};
8. The Service Worker will now control pages,
but only those opened after the register() is
successful. i.e. a document starts life with or
without a Service Worker and maintains that
for its lifetime. So documents will have to be
reloaded to actually be controlled.
this.addEventListener('fetch', function(event) {
var cachedResponse = caches.match(event.request).catch
(function() {
return event.default().then(function(response) {
return caches.get('v1').then(function(cache) {
cache.put(event.request, response.clone());
return response;
});
});
}).catch(function() {
return caches.match('/sw-test/gallery/myLittleVader.jpg');
});
event.respondWith(cachedResponse);
});
When to use?
Cache assets specific to the version of
the app
Give the user a "Read later" or "Save
for offline" button. When it's clicked,
fetch what you need from the network &
pop it in the cache.
On network response: Frequently
updating resources such as a user's
inbox, tweets, images, or article
contents.
Push
● The Push API is built on top of SerivceWorker.
● Allows the ServiceWorker to be awoken in response to
a message from the OS's messaging service.
● Happens even when the user doesn't have a tab open
to your site, only the ServiceWorker is woken up.
● You request permission to do this from a page & the
user will be prompted.
Background Sync
● Built on top of ServiceWorker.
● It allows you to request background data
synchronisation as a one-off, or on an (extremely
heuristic) interval.
● This happens even when the user doesn't have a tab
open to your site, only the ServiceWorker is woken up.
● You request permission to do this from a page & the
user will be prompted.
The bad news
● If installation fails, the browser is not good at
telling you about it
● fetch() is only available in service workers
● No credentials by default (cookies)
● Non-CORS fail by default (opaque response)
● Handling responsive images
Demo
Questions

More Related Content

What's hot

Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous JavascriptGarrett Welson
 
Asynchronous javascript
 Asynchronous javascript Asynchronous javascript
Asynchronous javascriptEman Mohamed
 
Introducing Async/Await
Introducing Async/AwaitIntroducing Async/Await
Introducing Async/AwaitValeri Karpov
 
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Edureka!
 
Angular 16 – the rise of Signals
Angular 16 – the rise of SignalsAngular 16 – the rise of Signals
Angular 16 – the rise of SignalsCoding Academy
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectJadson Santos
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data BindingDuy Khanh
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Knoldus Inc.
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
Rest presentation
Rest  presentationRest  presentation
Rest presentationsrividhyau
 
Selenium WebDriver
Selenium WebDriverSelenium WebDriver
Selenium WebDriverRajathi-QA
 
Angular tutorial
Angular tutorialAngular tutorial
Angular tutorialRohit Gupta
 

What's hot (20)

Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
Ajax Presentation
Ajax PresentationAjax Presentation
Ajax Presentation
 
Asynchronous javascript
 Asynchronous javascript Asynchronous javascript
Asynchronous javascript
 
Async js
Async jsAsync js
Async js
 
Pwa.pptx
Pwa.pptxPwa.pptx
Pwa.pptx
 
Introducing Async/Await
Introducing Async/AwaitIntroducing Async/Await
Introducing Async/Await
 
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
 
Angular 16 – the rise of Signals
Angular 16 – the rise of SignalsAngular 16 – the rise of Signals
Angular 16 – the rise of Signals
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete project
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
jQuery Ajax
jQuery AjaxjQuery Ajax
jQuery Ajax
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Webpack slides
Webpack slidesWebpack slides
Webpack slides
 
Rest presentation
Rest  presentationRest  presentation
Rest presentation
 
Selenium WebDriver
Selenium WebDriverSelenium WebDriver
Selenium WebDriver
 
Angular tutorial
Angular tutorialAngular tutorial
Angular tutorial
 
Angularjs PPT
Angularjs PPTAngularjs PPT
Angularjs PPT
 
Angular 9
Angular 9 Angular 9
Angular 9
 

Similar to Service Worker Presentation

"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 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
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAnkit Agarwal
 
Introduction to Service Workers | Matteo Manchi
Introduction to Service Workers | Matteo ManchiIntroduction to Service Workers | Matteo Manchi
Introduction to Service Workers | Matteo ManchiCodemotion
 
JSChannel 2017 - Service Workers and the Role they Play in modern day web-apps
JSChannel 2017 - Service Workers and the Role they Play in modern day web-appsJSChannel 2017 - Service Workers and the Role they Play in modern day web-apps
JSChannel 2017 - Service Workers and the Role they Play in modern day web-appsMukul Jain
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...WebStackAcademy
 
Service Worker - Reliability bits
Service Worker - Reliability bitsService Worker - Reliability bits
Service Worker - Reliability bitsjungkees
 
[1C1]Service Workers
[1C1]Service Workers[1C1]Service Workers
[1C1]Service WorkersNAVER D2
 
Apache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's NextApache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's NextPrateek Maheshwari
 
Mage Titans - Workshop - UI Components
Mage Titans - Workshop - UI ComponentsMage Titans - Workshop - UI Components
Mage Titans - Workshop - UI Componentsvkorotun
 
Ajax tutorial by bally chohan
Ajax tutorial by bally chohanAjax tutorial by bally chohan
Ajax tutorial by bally chohanWebVineet
 
Async Server Rendering in React+Redux at NYTimes (redux-taxi)
Async Server Rendering in React+Redux at NYTimes (redux-taxi)Async Server Rendering in React+Redux at NYTimes (redux-taxi)
Async Server Rendering in React+Redux at NYTimes (redux-taxi)Jeremy Gayed
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 
Offline First with Service Worker
Offline First with Service WorkerOffline First with Service Worker
Offline First with Service WorkerMuhammad Samu
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in reactBOSC Tech Labs
 

Similar to Service Worker Presentation (20)

"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 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
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
Introduction to Service Workers | Matteo Manchi
Introduction to Service Workers | Matteo ManchiIntroduction to Service Workers | Matteo Manchi
Introduction to Service Workers | Matteo Manchi
 
JSChannel 2017 - Service Workers and the Role they Play in modern day web-apps
JSChannel 2017 - Service Workers and the Role they Play in modern day web-appsJSChannel 2017 - Service Workers and the Role they Play in modern day web-apps
JSChannel 2017 - Service Workers and the Role they Play in modern day web-apps
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 1...
 
Service Worker - Reliability bits
Service Worker - Reliability bitsService Worker - Reliability bits
Service Worker - Reliability bits
 
[1C1]Service Workers
[1C1]Service Workers[1C1]Service Workers
[1C1]Service Workers
 
Service workers
Service workersService workers
Service workers
 
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
 
Ajax
AjaxAjax
Ajax
 
Apache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's NextApache Samza 1.0 - What's New, What's Next
Apache Samza 1.0 - What's New, What's Next
 
Mage Titans - Workshop - UI Components
Mage Titans - Workshop - UI ComponentsMage Titans - Workshop - UI Components
Mage Titans - Workshop - UI Components
 
Ajax tutorial by bally chohan
Ajax tutorial by bally chohanAjax tutorial by bally chohan
Ajax tutorial by bally chohan
 
Async Server Rendering in React+Redux at NYTimes (redux-taxi)
Async Server Rendering in React+Redux at NYTimes (redux-taxi)Async Server Rendering in React+Redux at NYTimes (redux-taxi)
Async Server Rendering in React+Redux at NYTimes (redux-taxi)
 
Ajax
AjaxAjax
Ajax
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Offline First with Service Worker
Offline First with Service WorkerOffline First with Service Worker
Offline First with Service Worker
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in react
 
Ajax
AjaxAjax
Ajax
 

Service Worker Presentation

  • 2. Overview ● What is a Service Worker? ● What existed before the Service Worker? ● Lifecycle of a Service Worker ● Use cases ● A fair assessment (a.k.a. the bad)
  • 3. What is a service worker?
  • 4. A service worker is a script that is run by your browser in the background, separate from a web page
  • 5. ● It's a JavaScript Worker, so it can't access the DOM directly ● Service worker is a programmable network proxy, allowing you to control how network requests from your page are handled. ● It will be terminated when not in use, and restarted when it's next needed ● Service workers are asynchronous and make extensive use of promises ● Service workers require content to be served via https
  • 6. What existed before the Service Worker?
  • 10.
  • 12. 1. The service worker URL is fetched and registered if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/trained-to-thrill/sw.js') .then(function(reg) { console.log('success!', reg); }, function(err) { console.log('error!', err); }); }
  • 13. 2. If successful, the service worker is executed in a ServiceWorkerGlobalScope; this is basically a special kind of worker context, running off the main script execution thread, with no DOM access. 3. The service worker is now ready to process events.
  • 14. 4. Installation of the worker is attempted when service worker- controlled pages are accessed subsequently. An Install event is always the first one sent to a service worker 5. Same procedure as installing a native app — making everything available for use offline.
  • 15. 6. When the oninstall handler completes, the service worker is considered installed. self.oninstall = function(event) { event.waitUntil( caches.open('trains-static-v14').then(function(cache) { return cache.addAll([ '/trained-to-thrill/', '/trained-to-thrill/static/css/all.css', '/trained-to-thrill/static/js/page.js', '/trained-to-thrill/static/imgs/logo.svg', '/trained-to-thrill/static/imgs/icon.png' ]); }) ); };
  • 16. 7. When the service worker is installed, it then receives an activate event. The primary use of onactivate is for cleanup of resources used in previous versions of a Service Worker script. self.onactivate = function(event) { // remove caches beginning "trains-" that aren't in // expectedCaches event.waitUntil( caches.keys().then(function(cacheNames) { return Promise.all( cacheNames.map(function(cacheName) { if (!/^trains-/.test(cacheName)) { return; } if (expectedCaches.indexOf(cacheName) == -1) { return caches.delete(cacheName); }}));}));};
  • 17. 8. The Service Worker will now control pages, but only those opened after the register() is successful. i.e. a document starts life with or without a Service Worker and maintains that for its lifetime. So documents will have to be reloaded to actually be controlled. this.addEventListener('fetch', function(event) { var cachedResponse = caches.match(event.request).catch (function() { return event.default().then(function(response) { return caches.get('v1').then(function(cache) { cache.put(event.request, response.clone()); return response; }); }); }).catch(function() { return caches.match('/sw-test/gallery/myLittleVader.jpg'); }); event.respondWith(cachedResponse); });
  • 19. Cache assets specific to the version of the app
  • 20. Give the user a "Read later" or "Save for offline" button. When it's clicked, fetch what you need from the network & pop it in the cache.
  • 21. On network response: Frequently updating resources such as a user's inbox, tweets, images, or article contents.
  • 22. Push ● The Push API is built on top of SerivceWorker. ● Allows the ServiceWorker to be awoken in response to a message from the OS's messaging service. ● Happens even when the user doesn't have a tab open to your site, only the ServiceWorker is woken up. ● You request permission to do this from a page & the user will be prompted.
  • 23. Background Sync ● Built on top of ServiceWorker. ● It allows you to request background data synchronisation as a one-off, or on an (extremely heuristic) interval. ● This happens even when the user doesn't have a tab open to your site, only the ServiceWorker is woken up. ● You request permission to do this from a page & the user will be prompted.
  • 25.
  • 26. ● If installation fails, the browser is not good at telling you about it ● fetch() is only available in service workers ● No credentials by default (cookies) ● Non-CORS fail by default (opaque response) ● Handling responsive images
  • 27. Demo