SlideShare a Scribd company logo
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 Worker
Chang W. Doh
 
Service worker - Offline Web
Service worker - Offline WebService worker - Offline Web
Service worker - Offline Web
Bruno 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 Vacay
Natasha Rooney
 
JQuery UK Service Workers Talk
JQuery UK Service Workers TalkJQuery UK Service Workers Talk
JQuery UK Service Workers Talk
Natasha 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 Training
Patrick 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 apps
Mukul Jain
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript Framework
All 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 App
Muhammad 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 & Routes
Nick Dreckshage
 
WordPress 2017 with VueJS and GraphQL
WordPress 2017 with VueJS and GraphQLWordPress 2017 with VueJS and GraphQL
WordPress 2017 with VueJS and GraphQL
houzman
 
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
Ryan Weaver
 
Velocity 2014 nyc WebPagetest private instances
Velocity 2014 nyc   WebPagetest private instancesVelocity 2014 nyc   WebPagetest private instances
Velocity 2014 nyc WebPagetest private instances
Patrick 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 Nikita
WordCamp 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 2010
Nicholas Zakas
 
So I Wrote a Manifest
So I Wrote a ManifestSo I Wrote a Manifest
So I Wrote a Manifest
Puppet
 
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
drupalindia
 
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
Nicholas 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 devices
Windows Developer
 
Progressive Web Apps - Intro & Learnings
Progressive Web Apps - Intro & LearningsProgressive Web Apps - Intro & Learnings
Progressive Web Apps - Intro & Learnings
Johannes Weber
 
GDG Ibadan #pwa
GDG Ibadan #pwaGDG Ibadan #pwa
GDG Ibadan #pwa
Gbolahan Alli
 
Progressive Web Apps 101
Progressive Web Apps 101Progressive Web Apps 101
Progressive Web Apps 101
Muhammad Samu
 
Love at first Vue
Love at first VueLove at first Vue
Love at first Vue
Dalibor Gogic
 
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 2
Manfred Steyer
 
Progressive Web Apps
Progressive Web AppsProgressive Web Apps
Progressive Web Apps
Johannes Weber
 
Building cross platform web apps
Building cross platform web appsBuilding cross platform web apps
Building cross platform web apps
ITEM
 
PWA
PWAPWA
Progressive Web Apps - NPD Meet
Progressive Web Apps - NPD MeetProgressive Web Apps - NPD Meet
Progressive Web Apps - NPD Meet
Vaideeswaran Sethuraman
 
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 Apps
FITC
 
Google Cloud Platform
Google Cloud Platform Google Cloud Platform
Google Cloud Platform
Francesco Marchitelli
 
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
murtazahaveliwala
 
Mean stack Magics
Mean stack MagicsMean stack Magics
Mean stack Magics
Aishura Aishu
 
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 iOS
FITC
 

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

Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 

Recently uploaded (20)

Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 

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