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

Contenu connexe

Tendances

Tendances (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
 

Similaire à Service workers

openMIC barcamp 11.02.2010
openMIC barcamp 11.02.2010openMIC barcamp 11.02.2010
openMIC barcamp 11.02.2010
Patrick Lauke
 
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
FITC
 

Similaire à 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
 

Dernier

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

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