SlideShare a Scribd company logo
SERVICE WORKERS
E O SEU PAPEL NA CRIAÇÃO DE PWAS
ARTUR FELIPE DE SOUSA
https://github.com/arturfsousa

https://twitter.com/arturfsousa

arturfelipe.sousa@gmail.com
WEB WORKERS
Execução de scripts fora da main thread
WEB WORKERS
VANTAGENS
‣ Não bloqueantes
‣ Comunicação via postMessage() e onmessage
‣ I/O via XMLHttpRequest
‣ Acessam Data Storages
‣ importScripts()
WEB WORKERS
DESVANTAGENS
‣ Não manipulam o DOM
‣ Não acessam window, document e parent
‣ Trafego de dados pode ser custoso
<script>
function doSomeHeavyStuff() {
const input = parseInt(document.getElementById('input').value, 10);
const result = summation(input);
document.getElementById('result').innerText = `Result: ${result}`;
}
function summation(n) {
let result = 0;
for (let i = 0; i <= n; i++) {
result += i;
}
return result;
}
</script>
SEM WORKER
demo-no-worker.html
https://github.com/arturfelipe/webworkers-demo
<script>
function doSomeHeavyStuff() {
const input = parseInt(document.getElementById('input').value, 10);
worker.postMessage(input);
}
const worker = new Worker('webworker.js');
worker.addEventListener('message', function(e) {
document.getElementById('result').innerText = `Result: ${e.data}`;
}, false);
</script>
COM WORKER
demo-worker.html
function summation(n) {
let result = 0;
for (let i = 0; i <= n; i++) {
result += i;
}
return result;
}
self.addEventListener('message', function(e) {
const result = summation(e.data);
self.postMessage(result);
}, false);
webworker.js
TROCA DE MENSAGENS
SEM WORKER
COM WORKER
VOU USAR AONDE?
WEB WORKERS
EXEMPLOS PRÁTICOS
‣ Análise de dados de audio, vídeo e imagem
‣ Análise pesada de texto (megadraft)
‣ Polling de serviços
‣ Processamento de arrays ou JSON gigantes
DOM CHANGELIST
SHARED ARRAY BUFFER
http://lucasfcosta.com/2017/04/30/JavaScript-From-Workers-to-Shared-Memory.html

https://github.com/whatwg/dom/issues/270

https://www.youtube.com/watch?v=q5HDhQtpDRU (2:00-10:10)
SERVICE WORKERS
Proxy de rede programável
Fonte: Vaadin
SERVICE WORKERS
CARACTERÍSTICAS
‣ É um Web Worker
‣ Intercepção e controle de requests/responses
‣ Cache de responses via Cache API
‣ Acesso a IndexedDB API
‣ Offline
‣ Só funcionam com HTTPS
CACHE API
Mecanismo de storage de pares Request/Response
caches.open('mycache')
.then(cache => {
const request = new Request('/');
const responseHeaders = { headers: { 'content-type': 'text/html' } };
const response = new Response('<h1>Hello</h1>', responseHeaders);
cache.put(request, response);
})
INDEXED DB
Mecanismo de storage indexado com suporte a objetos
let req = indexedDB.open('mydb', 1);
req.onsuccess = function() {
let dataBase = this.result;
let transaction = dataBase.transaction('beer', 'readwrite');
let store = transaction.objectStore('beer');
store.add({ name: 'La chouffe', type: 'Belgian Specialty Ale' });
};
req.onupgradeneeded = function(e) {
let store = e.currentTarget.result.createObjectStore('beer', {
keyPath: 'id',
autoIncrement: true
});
store.createIndex('name', 'name', { unique: true });
store.createIndex('type', 'type', { unique: false });
};
CICLO DE VIDA SW
SEM SERVICE WORKER (Primeiro Acesso)
Instalação
ErroAtivação
Idle
Finalizado
Fetch / Messages
navigator.serviceWorker.register('/sw.js')
Precache
CacheStorage cleanup
Runtime caching
WEBAPP
BACKGROUND
DEMO
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(register => {
console.log('[WEB] Service Worker registered :P', register);
})
.catch(err => {
console.log('[WEB] Service Worker fail to register :/', err);
});
}
function orderBeer() {
const img = new Image();
img.src = '/img/beer.svg';
img.className = 'beer';
document.getElementById('bar').appendChild(img);
}
</script>
index.html
REGISTRO
const CACHE_VERSION = 'v1';
const CACHE_NAME = `some-cool-bar-${CACHE_VERSION}`;
self.addEventListener('install', event => {
console.log(`[SW] Installing ${CACHE_NAME}`);
// Precaching
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => {
console.log(`[SW] Precaching ${CACHE_NAME}`);
return cache.addAll([
'/',
'/img/beer.svg',
'/img/bar.svg',
'/img/milk.svg'
])
})
);
});
sw.js
INSTALAÇÃO
PRECACHING
self.addEventListener('activate', event => {
console.log(`[SW] Activated ${CACHE_NAME}`);
// Cache cleanup
event.waitUntil(
caches.keys()
.then(cacheNames => Promise.all(
cacheNames.map(cacheName => {
if (cacheName != CACHE_NAME) {
return caches.delete(cacheName);
}
})
))
);
});
sw.js
ATIVAÇÃO
CACHE CLEANUP
clients.claim();
Força o controle do SW
self.addEventListener('fetch', event => {
console.log(`[SW] Handling fetch ${CACHE_NAME}`);
event.respondWith(
caches.match(event.request)
.then(function(response) {
const url = new URL(event.request.url);
// Serve a glass of milk instead of a beer
if (url.origin == location.origin && url.pathname.endsWith('/img/beer.svg')) {
return caches.match('/img/milk.svg');
}
// Cache hit - return response from cache
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});
sw.js
FETCH
RUNTIME CACHING / CONTROLE DE REQUESTS
https://developers.google.com/web/tools/workbox/
WIZARD
AUTO GERAÇÃO DO SW
module.exports = {
"globDirectory": "dist/",
"globPatterns": [
"**/*.{svg,html}"
],
"swDest": "dist/sw.js",
"swSrc": "src/sw.js"
};
workbox-config.js
TEMPLATE
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0-alpha.3/workbox-sw.js');
workbox.clientsClaim();
// Milk trick
workbox.routing.registerRoute(
//img/beer.svg$/,
() => caches.match('/img/milk.svg')
);
workbox.precaching.precacheAndRoute([]);
src/sw.js
Estratégia de cache
SW GERADO
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0-alpha.3/workbox-sw.js');
workbox.clientsClaim();
// Milk trick
workbox.routing.registerRoute(
//img/beer.svg$/,
() => caches.match('/img/milk.svg')
);
workbox.precaching.precacheAndRoute([
{
"url": "img/bar.svg",
"revision": "d86c626f2caadc7f73f5987f9af611b6"
},
{
"url": "img/beer.svg",
"revision": "30b921568452c89dfbafa350f6263fc7"
},
{
"url": "img/milk.svg",
"revision": "4f18cee564ab485eea01bed8cab7b856"
},
{
"url": "index.html",
"revision": "0edb00801da856632d63a14928efc4bd"
}
]);
dist/sw.js
Hash baseado no conteúdo dos arquivos
WORKBOX
ESTRATÉGIAS DE CACHE
‣ cacheFirst
‣ cacheOnly
‣ networkFirst
‣ networkOnly
‣ staleWhileRevalidate
PUSH NOTIFICATIONS
BACKGROUND SYNC
https://www.youtube.com/watch?v=l4e_LFozK2k
PROGRESSIVE WEB APPS
CONJUNTO DE CONCEITOS
MELHORIAS
NOVAS FEATURES DA WEB
MELHORAR A EXPERIÊNCIA
Performance
Service Workers
Offline
Push Notifications Background Sync
Add to Home Screen
CredentialsPayment
MOM
Measure

Optimize

Monitor
Speed Curve
WebPageTest
LightHouse
RUM
Mundo REAL
Real User Monitor
OBRIGADO
Referências em:
https://github.com/arturfsousa/serviceworkers-demo/blob/master/REFERENCES.md

More Related Content

What's hot

49368010 projectreportontraininganddevelopment(1)
49368010 projectreportontraininganddevelopment(1)49368010 projectreportontraininganddevelopment(1)
49368010 projectreportontraininganddevelopment(1)
Kritika910
 
JAVASCRIPT NÃO-OBSTRUTIVO com jQuery
JAVASCRIPT NÃO-OBSTRUTIVO com jQueryJAVASCRIPT NÃO-OBSTRUTIVO com jQuery
JAVASCRIPT NÃO-OBSTRUTIVO com jQuery
Zigotto Tecnologia
 
Introdução a worker 2.0
Introdução a worker 2.0Introdução a worker 2.0
Introdução a worker 2.0
Sérgio Rafael Siqueira
 
A new way to develop with WordPress!
A new way to develop with WordPress!A new way to develop with WordPress!
A new way to develop with WordPress!
David Sanchez
 
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and JasmineRails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Raimonds Simanovskis
 
Compatibility Detector Tool of Chrome extensions
Compatibility Detector Tool of Chrome extensionsCompatibility Detector Tool of Chrome extensions
Compatibility Detector Tool of Chrome extensions
Kai Cui
 
Getting classy with ES6
Getting classy with ES6Getting classy with ES6
Getting classy with ES6
Andy Sharman
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
Eyal Vardi
 
ZF3 introduction
ZF3 introductionZF3 introduction
ZF3 introduction
Vincent Blanchon
 
AngularJS Animations
AngularJS AnimationsAngularJS Animations
AngularJS Animations
Eyal Vardi
 
RSpec
RSpecRSpec
Javascript - Beyond-jQuery
Javascript - Beyond-jQueryJavascript - Beyond-jQuery
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards
Denis Ristic
 
Rails is not just Ruby
Rails is not just RubyRails is not just Ruby
Rails is not just Ruby
Marco Otte-Witte
 
amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5
mennovanslooten
 
Excellent
ExcellentExcellent
Excellent
Marco Otte-Witte
 
The new features of PHP 7
The new features of PHP 7The new features of PHP 7
The new features of PHP 7
Zend by Rogue Wave Software
 
06 jQuery #burningkeyboards
06 jQuery  #burningkeyboards06 jQuery  #burningkeyboards
06 jQuery #burningkeyboards
Denis Ristic
 
AngularJS $Provide Service
AngularJS $Provide ServiceAngularJS $Provide Service
AngularJS $Provide Service
Eyal Vardi
 
Ruby - Design patterns tdc2011
Ruby - Design patterns tdc2011Ruby - Design patterns tdc2011
Ruby - Design patterns tdc2011
Rafael Felix da Silva
 

What's hot (20)

49368010 projectreportontraininganddevelopment(1)
49368010 projectreportontraininganddevelopment(1)49368010 projectreportontraininganddevelopment(1)
49368010 projectreportontraininganddevelopment(1)
 
JAVASCRIPT NÃO-OBSTRUTIVO com jQuery
JAVASCRIPT NÃO-OBSTRUTIVO com jQueryJAVASCRIPT NÃO-OBSTRUTIVO com jQuery
JAVASCRIPT NÃO-OBSTRUTIVO com jQuery
 
Introdução a worker 2.0
Introdução a worker 2.0Introdução a worker 2.0
Introdução a worker 2.0
 
A new way to develop with WordPress!
A new way to develop with WordPress!A new way to develop with WordPress!
A new way to develop with WordPress!
 
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and JasmineRails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript using CoffeeScript, Backbone.js and Jasmine
 
Compatibility Detector Tool of Chrome extensions
Compatibility Detector Tool of Chrome extensionsCompatibility Detector Tool of Chrome extensions
Compatibility Detector Tool of Chrome extensions
 
Getting classy with ES6
Getting classy with ES6Getting classy with ES6
Getting classy with ES6
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
 
ZF3 introduction
ZF3 introductionZF3 introduction
ZF3 introduction
 
AngularJS Animations
AngularJS AnimationsAngularJS Animations
AngularJS Animations
 
RSpec
RSpecRSpec
RSpec
 
Javascript - Beyond-jQuery
Javascript - Beyond-jQueryJavascript - Beyond-jQuery
Javascript - Beyond-jQuery
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards
 
Rails is not just Ruby
Rails is not just RubyRails is not just Ruby
Rails is not just Ruby
 
amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5
 
Excellent
ExcellentExcellent
Excellent
 
The new features of PHP 7
The new features of PHP 7The new features of PHP 7
The new features of PHP 7
 
06 jQuery #burningkeyboards
06 jQuery  #burningkeyboards06 jQuery  #burningkeyboards
06 jQuery #burningkeyboards
 
AngularJS $Provide Service
AngularJS $Provide ServiceAngularJS $Provide Service
AngularJS $Provide Service
 
Ruby - Design patterns tdc2011
Ruby - Design patterns tdc2011Ruby - Design patterns tdc2011
Ruby - Design patterns tdc2011
 

Similar to Service Workers

Taking Web Apps Offline
Taking Web Apps OfflineTaking Web Apps Offline
Taking Web Apps Offline
Pedro Morais
 
Scti 2011 minicurso jquery
Scti 2011 minicurso jqueryScti 2011 minicurso jquery
Scti 2011 minicurso jquery
ciberglo
 
JavaScript Web Workers
JavaScript Web WorkersJavaScript Web Workers
JavaScript Web Workers
Tobias Pfeiffer
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
dion
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
Igor Bronovskyy
 
Mobile webapplication development
Mobile webapplication developmentMobile webapplication development
Mobile webapplication development
Ganesh Gembali
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
Mike Subelsky
 
Play! Framework for JavaEE Developers
Play! Framework for JavaEE DevelopersPlay! Framework for JavaEE Developers
Play! Framework for JavaEE Developers
Teng Shiu Huang
 
Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"
EPAM Systems
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
pootsbook
 
HTML5 & The Open Web - at Nackademin
HTML5 & The Open Web -  at NackademinHTML5 & The Open Web -  at Nackademin
HTML5 & The Open Web - at Nackademin
Robert Nyman
 
How to make Ajax work for you
How to make Ajax work for youHow to make Ajax work for you
How to make Ajax work for you
Simon Willison
 
Express Presentation
Express PresentationExpress Presentation
Express Presentation
aaronheckmann
 
The Browser Environment - A Systems Programmer's Perspective [sinatra edition]
The Browser Environment - A Systems Programmer's Perspective [sinatra edition]The Browser Environment - A Systems Programmer's Perspective [sinatra edition]
The Browser Environment - A Systems Programmer's Perspective [sinatra edition]
Eleanor McHugh
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Rails GUI Development with Ext JS
Rails GUI Development with Ext JSRails GUI Development with Ext JS
Rails GUI Development with Ext JS
Martin Rehfeld
 
Open Source Ajax Solution @OSDC.tw 2009
Open Source Ajax  Solution @OSDC.tw 2009Open Source Ajax  Solution @OSDC.tw 2009
Open Source Ajax Solution @OSDC.tw 2009
Robbie Cheng
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
Francois Zaninotto
 
Introduction to AJAX and DWR
Introduction to AJAX and DWRIntroduction to AJAX and DWR
Introduction to AJAX and DWR
SweNz FixEd
 
The Open Web and what it means
The Open Web and what it meansThe Open Web and what it means
The Open Web and what it means
Robert Nyman
 

Similar to Service Workers (20)

Taking Web Apps Offline
Taking Web Apps OfflineTaking Web Apps Offline
Taking Web Apps Offline
 
Scti 2011 minicurso jquery
Scti 2011 minicurso jqueryScti 2011 minicurso jquery
Scti 2011 minicurso jquery
 
JavaScript Web Workers
JavaScript Web WorkersJavaScript Web Workers
JavaScript Web Workers
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
 
Mobile webapplication development
Mobile webapplication developmentMobile webapplication development
Mobile webapplication development
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
Play! Framework for JavaEE Developers
Play! Framework for JavaEE DevelopersPlay! Framework for JavaEE Developers
Play! Framework for JavaEE Developers
 
Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"Владимир Мигуро "Дао Node.js"
Владимир Мигуро "Дао Node.js"
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
HTML5 & The Open Web - at Nackademin
HTML5 & The Open Web -  at NackademinHTML5 & The Open Web -  at Nackademin
HTML5 & The Open Web - at Nackademin
 
How to make Ajax work for you
How to make Ajax work for youHow to make Ajax work for you
How to make Ajax work for you
 
Express Presentation
Express PresentationExpress Presentation
Express Presentation
 
The Browser Environment - A Systems Programmer's Perspective [sinatra edition]
The Browser Environment - A Systems Programmer's Perspective [sinatra edition]The Browser Environment - A Systems Programmer's Perspective [sinatra edition]
The Browser Environment - A Systems Programmer's Perspective [sinatra edition]
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Rails GUI Development with Ext JS
Rails GUI Development with Ext JSRails GUI Development with Ext JS
Rails GUI Development with Ext JS
 
Open Source Ajax Solution @OSDC.tw 2009
Open Source Ajax  Solution @OSDC.tw 2009Open Source Ajax  Solution @OSDC.tw 2009
Open Source Ajax Solution @OSDC.tw 2009
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
Introduction to AJAX and DWR
Introduction to AJAX and DWRIntroduction to AJAX and DWR
Introduction to AJAX and DWR
 
The Open Web and what it means
The Open Web and what it meansThe Open Web and what it means
The Open Web and what it means
 

Recently uploaded

Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
Sven Peters
 
What next after learning python programming basics
What next after learning python programming basicsWhat next after learning python programming basics
What next after learning python programming basics
Rakesh Kumar R
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
Peter Muessig
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
Remote DBA Services
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
mz5nrf0n
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
Hornet Dynamics
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
Requirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional SafetyRequirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional Safety
Ayan Halder
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
Alina Yurenko
 

Recently uploaded (20)

Microservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we workMicroservice Teams - How the cloud changes the way we work
Microservice Teams - How the cloud changes the way we work
 
What next after learning python programming basics
What next after learning python programming basicsWhat next after learning python programming basics
What next after learning python programming basics
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
 
Oracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptxOracle 23c New Features For DBAs and Developers.pptx
Oracle 23c New Features For DBAs and Developers.pptx
 
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
 
E-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet DynamicsE-commerce Development Services- Hornet Dynamics
E-commerce Development Services- Hornet Dynamics
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
Requirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional SafetyRequirement Traceability in Xen Functional Safety
Requirement Traceability in Xen Functional Safety
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query PerformanceUsing Query Store in Azure PostgreSQL to Understand Query Performance
Using Query Store in Azure PostgreSQL to Understand Query Performance
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
 

Service Workers

  • 1. SERVICE WORKERS E O SEU PAPEL NA CRIAÇÃO DE PWAS
  • 2. ARTUR FELIPE DE SOUSA https://github.com/arturfsousa
 https://twitter.com/arturfsousa
 arturfelipe.sousa@gmail.com
  • 3. WEB WORKERS Execução de scripts fora da main thread
  • 4. WEB WORKERS VANTAGENS ‣ Não bloqueantes ‣ Comunicação via postMessage() e onmessage ‣ I/O via XMLHttpRequest ‣ Acessam Data Storages ‣ importScripts()
  • 5. WEB WORKERS DESVANTAGENS ‣ Não manipulam o DOM ‣ Não acessam window, document e parent ‣ Trafego de dados pode ser custoso
  • 6.
  • 7. <script> function doSomeHeavyStuff() { const input = parseInt(document.getElementById('input').value, 10); const result = summation(input); document.getElementById('result').innerText = `Result: ${result}`; } function summation(n) { let result = 0; for (let i = 0; i <= n; i++) { result += i; } return result; } </script> SEM WORKER demo-no-worker.html https://github.com/arturfelipe/webworkers-demo
  • 8. <script> function doSomeHeavyStuff() { const input = parseInt(document.getElementById('input').value, 10); worker.postMessage(input); } const worker = new Worker('webworker.js'); worker.addEventListener('message', function(e) { document.getElementById('result').innerText = `Result: ${e.data}`; }, false); </script> COM WORKER demo-worker.html function summation(n) { let result = 0; for (let i = 0; i <= n; i++) { result += i; } return result; } self.addEventListener('message', function(e) { const result = summation(e.data); self.postMessage(result); }, false); webworker.js TROCA DE MENSAGENS
  • 12. WEB WORKERS EXEMPLOS PRÁTICOS ‣ Análise de dados de audio, vídeo e imagem ‣ Análise pesada de texto (megadraft) ‣ Polling de serviços ‣ Processamento de arrays ou JSON gigantes
  • 13. DOM CHANGELIST SHARED ARRAY BUFFER http://lucasfcosta.com/2017/04/30/JavaScript-From-Workers-to-Shared-Memory.html
 https://github.com/whatwg/dom/issues/270
 https://www.youtube.com/watch?v=q5HDhQtpDRU (2:00-10:10)
  • 14. SERVICE WORKERS Proxy de rede programável
  • 16. SERVICE WORKERS CARACTERÍSTICAS ‣ É um Web Worker ‣ Intercepção e controle de requests/responses ‣ Cache de responses via Cache API ‣ Acesso a IndexedDB API ‣ Offline ‣ Só funcionam com HTTPS
  • 17. CACHE API Mecanismo de storage de pares Request/Response caches.open('mycache') .then(cache => { const request = new Request('/'); const responseHeaders = { headers: { 'content-type': 'text/html' } }; const response = new Response('<h1>Hello</h1>', responseHeaders); cache.put(request, response); })
  • 18. INDEXED DB Mecanismo de storage indexado com suporte a objetos let req = indexedDB.open('mydb', 1); req.onsuccess = function() { let dataBase = this.result; let transaction = dataBase.transaction('beer', 'readwrite'); let store = transaction.objectStore('beer'); store.add({ name: 'La chouffe', type: 'Belgian Specialty Ale' }); }; req.onupgradeneeded = function(e) { let store = e.currentTarget.result.createObjectStore('beer', { keyPath: 'id', autoIncrement: true }); store.createIndex('name', 'name', { unique: true }); store.createIndex('type', 'type', { unique: false }); };
  • 19. CICLO DE VIDA SW SEM SERVICE WORKER (Primeiro Acesso) Instalação ErroAtivação Idle Finalizado Fetch / Messages navigator.serviceWorker.register('/sw.js') Precache CacheStorage cleanup Runtime caching WEBAPP BACKGROUND
  • 20. DEMO
  • 21. <script> if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js') .then(register => { console.log('[WEB] Service Worker registered :P', register); }) .catch(err => { console.log('[WEB] Service Worker fail to register :/', err); }); } function orderBeer() { const img = new Image(); img.src = '/img/beer.svg'; img.className = 'beer'; document.getElementById('bar').appendChild(img); } </script> index.html REGISTRO
  • 22. const CACHE_VERSION = 'v1'; const CACHE_NAME = `some-cool-bar-${CACHE_VERSION}`; self.addEventListener('install', event => { console.log(`[SW] Installing ${CACHE_NAME}`); // Precaching event.waitUntil( caches.open(CACHE_NAME) .then(cache => { console.log(`[SW] Precaching ${CACHE_NAME}`); return cache.addAll([ '/', '/img/beer.svg', '/img/bar.svg', '/img/milk.svg' ]) }) ); }); sw.js INSTALAÇÃO PRECACHING
  • 23. self.addEventListener('activate', event => { console.log(`[SW] Activated ${CACHE_NAME}`); // Cache cleanup event.waitUntil( caches.keys() .then(cacheNames => Promise.all( cacheNames.map(cacheName => { if (cacheName != CACHE_NAME) { return caches.delete(cacheName); } }) )) ); }); sw.js ATIVAÇÃO CACHE CLEANUP clients.claim(); Força o controle do SW
  • 24. self.addEventListener('fetch', event => { console.log(`[SW] Handling fetch ${CACHE_NAME}`); event.respondWith( caches.match(event.request) .then(function(response) { const url = new URL(event.request.url); // Serve a glass of milk instead of a beer if (url.origin == location.origin && url.pathname.endsWith('/img/beer.svg')) { return caches.match('/img/milk.svg'); } // Cache hit - return response from cache if (response) { return response; } return fetch(event.request); } ) ); }); sw.js FETCH RUNTIME CACHING / CONTROLE DE REQUESTS
  • 26. WIZARD AUTO GERAÇÃO DO SW module.exports = { "globDirectory": "dist/", "globPatterns": [ "**/*.{svg,html}" ], "swDest": "dist/sw.js", "swSrc": "src/sw.js" }; workbox-config.js
  • 28. SW GERADO importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.0.0-alpha.3/workbox-sw.js'); workbox.clientsClaim(); // Milk trick workbox.routing.registerRoute( //img/beer.svg$/, () => caches.match('/img/milk.svg') ); workbox.precaching.precacheAndRoute([ { "url": "img/bar.svg", "revision": "d86c626f2caadc7f73f5987f9af611b6" }, { "url": "img/beer.svg", "revision": "30b921568452c89dfbafa350f6263fc7" }, { "url": "img/milk.svg", "revision": "4f18cee564ab485eea01bed8cab7b856" }, { "url": "index.html", "revision": "0edb00801da856632d63a14928efc4bd" } ]); dist/sw.js Hash baseado no conteúdo dos arquivos
  • 29.
  • 30. WORKBOX ESTRATÉGIAS DE CACHE ‣ cacheFirst ‣ cacheOnly ‣ networkFirst ‣ networkOnly ‣ staleWhileRevalidate
  • 32. PROGRESSIVE WEB APPS CONJUNTO DE CONCEITOS MELHORIAS NOVAS FEATURES DA WEB
  • 33. MELHORAR A EXPERIÊNCIA Performance Service Workers Offline Push Notifications Background Sync Add to Home Screen CredentialsPayment
  • 35.