SlideShare a Scribd company logo
1 of 27
Download to read offline
Service Workers: into & usage
By: Pavel Zhytko (pjitco@gmail.com)
I. Why?
Ultimate Goal: Progressive Apps
* First who then what:
Alex Russell - Progressive Web Apps: Escaping Tabs Without Losing Our Soul
(June 15, 2015)
Addy Osmani - Getting started with Progressive Web Apps (Dec 23, 2015) <- A MUST!
Pete LePage (developers.google.com) - Your First Progressive Web App
Google Developers central repo
Stackoverflow tag
* what:
“A Progressive Web App uses modern web capabilities to deliver an app-like user experience.
They evolve from pages in browser tabs to immersive, top-level apps, maintaining the web's low
friction at every moment.
Progressive - Built with progressive enhancement as a core principle
Responsive - Fit any form factor, desktop, mobile, tablet, or whatever is next
Linkable - Easily share via URL and not require complex installation
App-like - Use the app-shell model to provide app-style navigations and interactions
Installable - Allow users to “keep” apps they find most useful on their home screen without
the hassle of an app store
Discoverable - Search engines can index it thanks to W3C manifests and SW scope
Connectivity independent - Enhanced with Service Workers to work offline
Fresh - Always up-to-date thanks to the Service Worker update process
Safe - Served via TLS to prevent tampering (a Service Worker requirement)
Re-engageable - Make re-engagement easy through features like push notifications
(Service Worker again)
Prior Art
Proprietary:
long list...
Open Web / Custom (MDN Demo):
Detect online/offline: Network Information API, Offline.js, ...
Fetch resources with XHR
Store resources to LocalSotrage/IndexedDB
Save state locally / sync with server: Firebase etc.
Open Web / App Cache
Bad attempt: Application Cache is a Douchebag (Jake Archibald, May 08, 2012)
Progressive - Built with progressive enhancement as a core principle
Responsive - Fit any form factor, desktop, mobile, tablet, or whatever is next
Linkable - Easily share via URL and not require complex installation
App-like - Use the app-shell model to provide app-style navigations and interactions
Installable - Allow users to “keep” apps they find most useful on their home screen without
the hassle of an app store
Discoverable - Search engines can index it thanks to W3C manifests and SW scope
Connectivity independent - Enhanced with Service Workers to work offline
Fresh - Always up-to-date thanks to the Service Worker update process
Safe - Served via TLS to prevent tampering (a Service Worker requirement)
Re-engageable - Make re-engagement easy through features like push notifications
(Service Worker again)
Progressive - Built with progressive enhancement as a core principle
Responsive - Fit any form factor, desktop, mobile, tablet, or whatever is next
Linkable - Easily share via URL and not require complex installation
App-like - Use the app-shell model to provide app-style navigations and interactions
Installable - Allow users to “keep” apps they find most useful on their home screen without
the hassle of an app store
Discoverable - Search engines can index it thanks to W3C manifests and SW scope
Connectivity independent - Enhanced with Service Workers to work offline
Fresh - Always up-to-date thanks to the Service Worker update process
Safe - Served via TLS to prevent tampering (a Service Worker requirement)
Re-engageable - Make re-engagement easy through features like push notifications
(Service Worker again)
Web App Manifest
“What every developer should do today — Google Developers
<link rel="manifest" href="/manifest.json">
{
"short_name": "Amaze App",
"name": "My Amazing Application ++",
"icons": [...],
"start_url": "/index.html",
"display": "standalone",
"orientation": "landscape"
}
Features:
Full-screen mode (without URL bar): (HTTPS only in Opera)
: "display""fullscreen"
or Standalone mode (just top bar):
: "display""standalone
Orientation: "orientation": "landscape"
Add to Home Screen menu
Plus heuristic for Add to Home Screen banner (tricky; cannot control but can cancel
and know if installed)
Splash Screen ( + + ) [Chrome 47]
"name""background_color""icons"
Theme color ( <meta name="theme-color" content="#db5945">)
Support:
- Chrome, FF, Opera
- Edge is considering
Tools:
- Web Starter Kit
- Manifest generator
- RealFaviconGenerator
II. How?
Registration
if('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/service-worker.js', {scope: './' })
.then(function() { console.log('Service Worker Registered'); });
}
- Call from arbitrary page: register() method of ServiceWorkerContainer interface
- Progressive enhancement
- Fetches .js file (HTTP caching respected)
- HTTPS only! (free SSL
certs:
LetsEncrypt.org)
- Location of file on server matters (defines max scope, relaxed with Service-Worker-Allowed
header)
- If successful, code executes in ServiceWorkerGlobalScope
ServiceWorkerGlobalScope and Workers
- Inherits from WokerGlobalScope - has limitations / features of other JS Workers: Web Workers,
Shared Workers, ...
- Separate thread (off the main script execution thread)
- Has limited abilities, notably: no DOM access!
- Has access to new features/API: Cache, Fetch, Request/Response, ... Uses Promises heavily.
- May use importScripts() to include other script files (even from other origin)
- May run even when all app pages are closed!
- Can (and will) be terminated to free memory, resumed on events
self.addEventListener('install', function(event) {/*...*/});
self.addEventListener('activate', function(event) {/*...*/});
self.addEventListener('fetch', function(event) {/*...*/});
self.addEventListener('push', function(event) {/*...*/});
Installation
- install event is triggered the first time the user visits the page (subsequent visit after
registration)
- this is the first event sent to SW
- when the oninstall handler completes, the service worker is considered installed
- good place to cache assets with Promise passed to event.waitUntil()
Caching on install
var filesToCache = ['/home/', '/home/index.html', '/home/style.css' ];
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open('v1').then(function(cache) {
return cache.addAll(filesToCache);
})
);
});
2.
- Need to add all permutations of file names ('/', '/index/html')
- If download of any resource fails - the promise is rejected and SW is not installed (OK - may be
installed next time)
- Cache may become full and cleared by browser.
Activation
- this step is required for SW update mechanism
- related to notion of controlled pages: even to fired until there are pages controlled by other
workers (previous version)
- new worker is considered the one that has any byte diff with old
- check state: chrome://serviceworker-internals/
- time to finish the installation, e.g. good place to remove old caches
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(keyList) {
return Promise.all(keyList.map(function(key) {
if (key !== 'v2') {
return caches.delete(key);
}
}));
})
);
});
Fetch
- this event with cache handling on install/activate enables Offline first
- essentially it acts as programmable network proxy
- takes Request and returns Response (Fetch API), which may be any of:
- new Response(body, opts)
- fetch(urlOrRequest)
- caches.match(urlOrRequest)
- resembles Express middleware!
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});
Resources and tooling
2 Cooking books:
- The offline cookbook [Jake Archibald]
- serviceworke.rs (Mozilla)
Tools:
By Google:
sw-precache - grunt/gulp script to generate assets list to cache with globs (to use in
install/cache.addAll() )
sw-toolbox - collection of tools to help writing event handlers, including Express-style middleware
importScripts('bower_components/sw-toolbox/sw-toolbox.js');
toolbox.precache(['/index.html', '/site.css', '/images/logo.png']); /*on install*/
toolbox.router.get(':foo/index.html$', function(request, values) {
return new Response('Some text');
});
toolbox.router.get('/myapp/index.html', toolbox.networkFirst); /* Use built-in handler
designed after a strategy in Offline Cookbook */
Beyond Offline
From serviceworke.rs Cookbook:
- API Analytics - intercept each request of a client and send some information to a log API
- Load Balancer - intercept the requests to the resources and select the proper content provider
accordingly to their availability
- Request Deferrer - enqueue requests while in offline in an outbox-like buffer to perform the
operations once the connection is regained
Push
New API
- Push API and Notification API [Chrome 42]
- Can use old Web Notifications too
- Web Push Protocol (implemented by 'web-push' NPM module)
Resources:
Push Notifications on the Open Web (Google Developers) - a lot of details
serviceworke.rs
Web Push notifications from Irssi (Mozilla Hacks)
Registration
var endpoint;
navigator.serviceWorker.register('service-worker.js').then(function(registration) {
return registration.pushManager.getSubscription().then(function(subscription) {
if (subscription) {
return subscription;
}
return registration.pushManager.subscribe({ userVisibleOnly: true });
});
}).then(function(subscription) {
endpoint = subscription.endpoint;
// Send endpoint to server to store in nDB
}
Send notification (server)
var webPush = require('web-push');
webPush.setGCMAPIKey(process.env.GCM_API_KEY);
// ...
webPush.sendNotification(endpoint, ttl);
Receive /show notification (Service Worker)
self.addEventListener('push', function(event) {
event.waitUntil(
self.registration.showNotification('New Discounts', {
lang: 'la',
body: 'Alea iacta est',
icon: 'caesar.jpg',
vibrate: [500, 100, 500],
})
);
});
Background Sync (in progress)
- Specification
- sync / periodycSync
navigator.serviceWorker.ready.then(function(registration) {
registration.sync.register('outbox').then(function() {
// registration succeeded
}
});
self.addEventListener('sync', function(event) {
if (event.tag == 'outbox') {
event.waitUntil(sendEverythingInTheOutbox());
}
});
III. When?
It is coming:
- isServiceWorkerReady
- waiting for Edge/Safari
Currently in production:
Flipkart Lite
Medium
Twitter
...
Q/A

More Related Content

What's hot

Instant and offline apps with Service Worker
Instant and offline apps with Service WorkerInstant and offline apps with Service Worker
Instant and offline apps with Service WorkerChang W. Doh
 
Service worker - Offline Web
Service worker - Offline WebService worker - Offline Web
Service worker - Offline WebBruno Oliveira
 
PWA 應用 - 實現網站離線瀏覽
PWA 應用 - 實現網站離線瀏覽PWA 應用 - 實現網站離線瀏覽
PWA 應用 - 實現網站離線瀏覽Anna Su
 
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
 
Front-End Single Point of Failure - Velocity 2016 Training
Front-End Single Point of Failure - Velocity 2016 TrainingFront-End Single Point of Failure - Velocity 2016 Training
Front-End Single Point of Failure - Velocity 2016 TrainingPatrick Meenan
 
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
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript FrameworkAll Things Open
 
"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
 
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
 
JS Chicago Meetup 2/23/16 - Redux & Routes
JS Chicago Meetup 2/23/16 - Redux & RoutesJS Chicago Meetup 2/23/16 - Redux & Routes
JS Chicago Meetup 2/23/16 - Redux & RoutesNick Dreckshage
 
WordPress 2017 with VueJS and GraphQL
WordPress 2017 with VueJS and GraphQLWordPress 2017 with VueJS and GraphQL
WordPress 2017 with VueJS and GraphQLhouzman
 
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other ToolsCool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other ToolsRyan Weaver
 
Velocity 2014 nyc WebPagetest private instances
Velocity 2014 nyc   WebPagetest private instancesVelocity 2014 nyc   WebPagetest private instances
Velocity 2014 nyc WebPagetest private instancesPatrick Meenan
 
Best Practices for creating WP REST API by Galkin Nikita
Best Practices for creating WP REST API by Galkin NikitaBest Practices for creating WP REST API by Galkin Nikita
Best Practices for creating WP REST API by Galkin NikitaWordCamp Kyiv
 
Enough with the JavaScript already!
Enough with the JavaScript already!Enough with the JavaScript already!
Enough with the JavaScript already!Nicholas Zakas
 
High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010Nicholas Zakas
 
So I Wrote a Manifest
So I Wrote a ManifestSo I Wrote a Manifest
So I Wrote a ManifestPuppet
 
Migraine Drupal - syncing your staging and live sites
Migraine Drupal - syncing your staging and live sitesMigraine Drupal - syncing your staging and live sites
Migraine Drupal - syncing your staging and live sitesdrupalindia
 
Forensic Tools for In-Depth Performance Investigations
Forensic Tools for In-Depth Performance InvestigationsForensic Tools for In-Depth Performance Investigations
Forensic Tools for In-Depth Performance InvestigationsNicholas Jansma
 

What's hot (20)

Instant and offline apps with Service Worker
Instant and offline apps with Service WorkerInstant and offline apps with Service Worker
Instant and offline apps with Service Worker
 
Service worker - Offline Web
Service worker - Offline WebService worker - Offline Web
Service worker - Offline Web
 
PWA 應用 - 實現網站離線瀏覽
PWA 應用 - 實現網站離線瀏覽PWA 應用 - 實現網站離線瀏覽
PWA 應用 - 實現網站離線瀏覽
 
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
 
Front-End Single Point of Failure - Velocity 2016 Training
Front-End Single Point of Failure - Velocity 2016 TrainingFront-End Single Point of Failure - Velocity 2016 Training
Front-End Single Point of Failure - Velocity 2016 Training
 
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
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript Framework
 
"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 "
 
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
 
JS Chicago Meetup 2/23/16 - Redux & Routes
JS Chicago Meetup 2/23/16 - Redux & RoutesJS Chicago Meetup 2/23/16 - Redux & Routes
JS Chicago Meetup 2/23/16 - Redux & Routes
 
WordPress 2017 with VueJS and GraphQL
WordPress 2017 with VueJS and GraphQLWordPress 2017 with VueJS and GraphQL
WordPress 2017 with VueJS and GraphQL
 
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other ToolsCool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
Cool like a Frontend Developer: Grunt, RequireJS, Bower and other Tools
 
Velocity 2014 nyc WebPagetest private instances
Velocity 2014 nyc   WebPagetest private instancesVelocity 2014 nyc   WebPagetest private instances
Velocity 2014 nyc WebPagetest private instances
 
Best Practices for creating WP REST API by Galkin Nikita
Best Practices for creating WP REST API by Galkin NikitaBest Practices for creating WP REST API by Galkin Nikita
Best Practices for creating WP REST API by Galkin Nikita
 
Enough with the JavaScript already!
Enough with the JavaScript already!Enough with the JavaScript already!
Enough with the JavaScript already!
 
High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010
 
So I Wrote a Manifest
So I Wrote a ManifestSo I Wrote a Manifest
So I Wrote a Manifest
 
Migraine Drupal - syncing your staging and live sites
Migraine Drupal - syncing your staging and live sitesMigraine Drupal - syncing your staging and live sites
Migraine Drupal - syncing your staging and live sites
 
Forensic Tools for In-Depth Performance Investigations
Forensic Tools for In-Depth Performance InvestigationsForensic Tools for In-Depth Performance Investigations
Forensic Tools for In-Depth Performance Investigations
 

Similar to 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 devicesWindows Developer
 
Progressive Web Apps - Intro & Learnings
Progressive Web Apps - Intro & LearningsProgressive Web Apps - Intro & Learnings
Progressive Web Apps - Intro & LearningsJohannes Weber
 
Progressive Web Apps 101
Progressive Web Apps 101Progressive Web Apps 101
Progressive Web Apps 101Muhammad Samu
 
Introduction aux progressive web apps
Introduction aux progressive web appsIntroduction aux progressive web apps
Introduction aux progressive web apps✅ William Pinaud
 
Progressive web apps with Angular 2
Progressive web apps with Angular 2Progressive web apps with Angular 2
Progressive web apps with Angular 2Manfred Steyer
 
Building cross platform web apps
Building cross platform web appsBuilding cross platform web apps
Building cross platform web appsITEM
 
Make your PWA feel more like an app
Make your PWA feel more like an appMake your PWA feel more like an app
Make your PWA feel more like an appÖnder Ceylan
 
Progressive Web Apps
Progressive Web AppsProgressive Web Apps
Progressive Web AppsFITC
 
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSAngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSmurtazahaveliwala
 
The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...
The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...
The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...Robert Nyman
 
openMIC barcamp 11.02.2010
openMIC barcamp 11.02.2010openMIC barcamp 11.02.2010
openMIC barcamp 11.02.2010Patrick Lauke
 
The web - What it has, what it lacks and where it must go - keynote at Riga D...
The web - What it has, what it lacks and where it must go - keynote at Riga D...The web - What it has, what it lacks and where it must go - keynote at Riga D...
The web - What it has, what it lacks and where it must go - keynote at Riga D...Robert Nyman
 
Building Progressive Web Apps for Android and iOS
Building Progressive Web Apps for Android and iOSBuilding Progressive Web Apps for Android and iOS
Building Progressive Web Apps for Android and iOSFITC
 

Similar to Service workers (20)

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
 
Progressive Web Apps - Intro & Learnings
Progressive Web Apps - Intro & LearningsProgressive Web Apps - Intro & Learnings
Progressive Web Apps - Intro & Learnings
 
GDG Ibadan #pwa
GDG Ibadan #pwaGDG Ibadan #pwa
GDG Ibadan #pwa
 
Progressive Web Apps 101
Progressive Web Apps 101Progressive Web Apps 101
Progressive Web Apps 101
 
Love at first Vue
Love at first VueLove at first Vue
Love at first Vue
 
Introduction aux progressive web apps
Introduction aux progressive web appsIntroduction aux progressive web apps
Introduction aux progressive web apps
 
Progressive web apps with Angular 2
Progressive web apps with Angular 2Progressive web apps with Angular 2
Progressive web apps with Angular 2
 
Progressive Web Apps
Progressive Web AppsProgressive Web Apps
Progressive Web Apps
 
Building cross platform web apps
Building cross platform web appsBuilding cross platform web apps
Building cross platform web apps
 
PWA
PWAPWA
PWA
 
Progressive Web Apps - NPD Meet
Progressive Web Apps - NPD MeetProgressive Web Apps - NPD Meet
Progressive Web Apps - NPD Meet
 
Make your PWA feel more like an app
Make your PWA feel more like an appMake your PWA feel more like an app
Make your PWA feel more like an app
 
Progressive Web Apps
Progressive Web AppsProgressive Web Apps
Progressive Web Apps
 
Google Cloud Platform
Google Cloud Platform Google Cloud Platform
Google Cloud Platform
 
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSAngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
 
Mean stack Magics
Mean stack MagicsMean stack Magics
Mean stack Magics
 
The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...
The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...
The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...
 
openMIC barcamp 11.02.2010
openMIC barcamp 11.02.2010openMIC barcamp 11.02.2010
openMIC barcamp 11.02.2010
 
The web - What it has, what it lacks and where it must go - keynote at Riga D...
The web - What it has, what it lacks and where it must go - keynote at Riga D...The web - What it has, what it lacks and where it must go - keynote at Riga D...
The web - What it has, what it lacks and where it must go - keynote at Riga D...
 
Building Progressive Web Apps for Android and iOS
Building Progressive Web Apps for Android and iOSBuilding Progressive Web Apps for Android and iOS
Building Progressive Web Apps for Android and iOS
 

Recently uploaded

New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 

Recently uploaded (20)

New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 

Service workers

  • 1. Service Workers: into & usage By: Pavel Zhytko (pjitco@gmail.com)
  • 3. Ultimate Goal: Progressive Apps * First who then what: Alex Russell - Progressive Web Apps: Escaping Tabs Without Losing Our Soul (June 15, 2015) Addy Osmani - Getting started with Progressive Web Apps (Dec 23, 2015) <- A MUST! Pete LePage (developers.google.com) - Your First Progressive Web App Google Developers central repo Stackoverflow tag * what: “A Progressive Web App uses modern web capabilities to deliver an app-like user experience. They evolve from pages in browser tabs to immersive, top-level apps, maintaining the web's low friction at every moment.
  • 4. Progressive - Built with progressive enhancement as a core principle Responsive - Fit any form factor, desktop, mobile, tablet, or whatever is next Linkable - Easily share via URL and not require complex installation App-like - Use the app-shell model to provide app-style navigations and interactions Installable - Allow users to “keep” apps they find most useful on their home screen without the hassle of an app store Discoverable - Search engines can index it thanks to W3C manifests and SW scope Connectivity independent - Enhanced with Service Workers to work offline Fresh - Always up-to-date thanks to the Service Worker update process Safe - Served via TLS to prevent tampering (a Service Worker requirement) Re-engageable - Make re-engagement easy through features like push notifications (Service Worker again)
  • 5. Prior Art Proprietary: long list... Open Web / Custom (MDN Demo): Detect online/offline: Network Information API, Offline.js, ... Fetch resources with XHR Store resources to LocalSotrage/IndexedDB Save state locally / sync with server: Firebase etc. Open Web / App Cache Bad attempt: Application Cache is a Douchebag (Jake Archibald, May 08, 2012)
  • 6. Progressive - Built with progressive enhancement as a core principle Responsive - Fit any form factor, desktop, mobile, tablet, or whatever is next Linkable - Easily share via URL and not require complex installation App-like - Use the app-shell model to provide app-style navigations and interactions Installable - Allow users to “keep” apps they find most useful on their home screen without the hassle of an app store Discoverable - Search engines can index it thanks to W3C manifests and SW scope Connectivity independent - Enhanced with Service Workers to work offline Fresh - Always up-to-date thanks to the Service Worker update process Safe - Served via TLS to prevent tampering (a Service Worker requirement) Re-engageable - Make re-engagement easy through features like push notifications (Service Worker again)
  • 7. Progressive - Built with progressive enhancement as a core principle Responsive - Fit any form factor, desktop, mobile, tablet, or whatever is next Linkable - Easily share via URL and not require complex installation App-like - Use the app-shell model to provide app-style navigations and interactions Installable - Allow users to “keep” apps they find most useful on their home screen without the hassle of an app store Discoverable - Search engines can index it thanks to W3C manifests and SW scope Connectivity independent - Enhanced with Service Workers to work offline Fresh - Always up-to-date thanks to the Service Worker update process Safe - Served via TLS to prevent tampering (a Service Worker requirement) Re-engageable - Make re-engagement easy through features like push notifications (Service Worker again)
  • 8. Web App Manifest “What every developer should do today — Google Developers <link rel="manifest" href="/manifest.json"> { "short_name": "Amaze App", "name": "My Amazing Application ++", "icons": [...], "start_url": "/index.html", "display": "standalone", "orientation": "landscape" }
  • 9. Features: Full-screen mode (without URL bar): (HTTPS only in Opera) : "display""fullscreen" or Standalone mode (just top bar): : "display""standalone Orientation: "orientation": "landscape" Add to Home Screen menu Plus heuristic for Add to Home Screen banner (tricky; cannot control but can cancel and know if installed) Splash Screen ( + + ) [Chrome 47] "name""background_color""icons" Theme color ( <meta name="theme-color" content="#db5945">) Support: - Chrome, FF, Opera - Edge is considering Tools: - Web Starter Kit - Manifest generator - RealFaviconGenerator
  • 11. Registration if('serviceWorker' in navigator) { navigator.serviceWorker .register('/service-worker.js', {scope: './' }) .then(function() { console.log('Service Worker Registered'); }); } - Call from arbitrary page: register() method of ServiceWorkerContainer interface - Progressive enhancement - Fetches .js file (HTTP caching respected) - HTTPS only! (free SSL certs: LetsEncrypt.org) - Location of file on server matters (defines max scope, relaxed with Service-Worker-Allowed header) - If successful, code executes in ServiceWorkerGlobalScope
  • 12. ServiceWorkerGlobalScope and Workers - Inherits from WokerGlobalScope - has limitations / features of other JS Workers: Web Workers, Shared Workers, ... - Separate thread (off the main script execution thread) - Has limited abilities, notably: no DOM access! - Has access to new features/API: Cache, Fetch, Request/Response, ... Uses Promises heavily. - May use importScripts() to include other script files (even from other origin) - May run even when all app pages are closed! - Can (and will) be terminated to free memory, resumed on events self.addEventListener('install', function(event) {/*...*/}); self.addEventListener('activate', function(event) {/*...*/}); self.addEventListener('fetch', function(event) {/*...*/}); self.addEventListener('push', function(event) {/*...*/});
  • 13. Installation - install event is triggered the first time the user visits the page (subsequent visit after registration) - this is the first event sent to SW - when the oninstall handler completes, the service worker is considered installed - good place to cache assets with Promise passed to event.waitUntil()
  • 14. Caching on install var filesToCache = ['/home/', '/home/index.html', '/home/style.css' ]; self.addEventListener('install', function(event) { event.waitUntil( caches.open('v1').then(function(cache) { return cache.addAll(filesToCache); }) ); }); 2. - Need to add all permutations of file names ('/', '/index/html') - If download of any resource fails - the promise is rejected and SW is not installed (OK - may be installed next time) - Cache may become full and cleared by browser.
  • 15. Activation - this step is required for SW update mechanism - related to notion of controlled pages: even to fired until there are pages controlled by other workers (previous version) - new worker is considered the one that has any byte diff with old - check state: chrome://serviceworker-internals/ - time to finish the installation, e.g. good place to remove old caches self.addEventListener('activate', function(event) { event.waitUntil( caches.keys().then(function(keyList) { return Promise.all(keyList.map(function(key) { if (key !== 'v2') { return caches.delete(key); } })); }) ); });
  • 16.
  • 17. Fetch - this event with cache handling on install/activate enables Offline first - essentially it acts as programmable network proxy - takes Request and returns Response (Fetch API), which may be any of: - new Response(body, opts) - fetch(urlOrRequest) - caches.match(urlOrRequest) - resembles Express middleware! self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request); }) ); });
  • 18. Resources and tooling 2 Cooking books: - The offline cookbook [Jake Archibald] - serviceworke.rs (Mozilla) Tools: By Google: sw-precache - grunt/gulp script to generate assets list to cache with globs (to use in install/cache.addAll() ) sw-toolbox - collection of tools to help writing event handlers, including Express-style middleware importScripts('bower_components/sw-toolbox/sw-toolbox.js'); toolbox.precache(['/index.html', '/site.css', '/images/logo.png']); /*on install*/ toolbox.router.get(':foo/index.html$', function(request, values) { return new Response('Some text'); }); toolbox.router.get('/myapp/index.html', toolbox.networkFirst); /* Use built-in handler designed after a strategy in Offline Cookbook */
  • 19. Beyond Offline From serviceworke.rs Cookbook: - API Analytics - intercept each request of a client and send some information to a log API - Load Balancer - intercept the requests to the resources and select the proper content provider accordingly to their availability - Request Deferrer - enqueue requests while in offline in an outbox-like buffer to perform the operations once the connection is regained
  • 20. Push New API - Push API and Notification API [Chrome 42] - Can use old Web Notifications too - Web Push Protocol (implemented by 'web-push' NPM module) Resources: Push Notifications on the Open Web (Google Developers) - a lot of details serviceworke.rs Web Push notifications from Irssi (Mozilla Hacks)
  • 21. Registration var endpoint; navigator.serviceWorker.register('service-worker.js').then(function(registration) { return registration.pushManager.getSubscription().then(function(subscription) { if (subscription) { return subscription; } return registration.pushManager.subscribe({ userVisibleOnly: true }); }); }).then(function(subscription) { endpoint = subscription.endpoint; // Send endpoint to server to store in nDB }
  • 22. Send notification (server) var webPush = require('web-push'); webPush.setGCMAPIKey(process.env.GCM_API_KEY); // ... webPush.sendNotification(endpoint, ttl);
  • 23. Receive /show notification (Service Worker) self.addEventListener('push', function(event) { event.waitUntil( self.registration.showNotification('New Discounts', { lang: 'la', body: 'Alea iacta est', icon: 'caesar.jpg', vibrate: [500, 100, 500], }) ); });
  • 24. Background Sync (in progress) - Specification - sync / periodycSync navigator.serviceWorker.ready.then(function(registration) { registration.sync.register('outbox').then(function() { // registration succeeded } }); self.addEventListener('sync', function(event) { if (event.tag == 'outbox') { event.waitUntil(sendEverythingInTheOutbox()); } });
  • 26. It is coming: - isServiceWorkerReady - waiting for Edge/Safari Currently in production: Flipkart Lite Medium Twitter ...
  • 27. Q/A