SlideShare una empresa de Scribd logo
1 de 39
Descargar para leer sin conexión
SERVICEWORKERS
E O FUTURO DAS APLICAÇÕES NO SEU BROWSER
EDUARDO MATOS
@eduardojmatos
LABORATÓRIO DE
PROGRAMAÇÃO*estamoscontratando!
POA É A
SAN FRANCISCO DO
BRASIL!
O QUE É UM WORKER?
Primeiradefinição de Worker surgiu com o WebWorkers
http://www.html5rocks.com/en/tutorials/workers/basics/
BROWSER EXECUTANDO
TAREFAS SEM BLOQUEAR
A INTERFACE
Resumindo: scripts rodando em paralelo àpagina
EX: tarefas que exigem alto processamento
//mainscript
varworker=newWorker('worker.js');
worker.addEventListener('message',function(e){
console.log('Workerdiz:',e.data);
},false);
worker.postMessage('Oi,eusouoWorker!');
//worker.js
self.addEventListener('message',function(e){
self.postMessage(e.data);
},false);
REGRAS COMUNS DE UM
WORKER
Não acessao DOM
Não acessao window
Não acessao document
Acessao navigator
Acessao location (ready-only)
E O SERVICEWORKERS?
Usao mesmo conceito do WebWorker de isolar execução de
um script
Controlaprogramaticamente o cache dasuaaplicação
Serve como um proxydasuaaplicação
[futuramente] BackgroundSync (!!)
[futuramente] Geofencing(!!!)
[futuramente] Push Notifications (!!!!)
[futuramente] Bluetooth (!!!!!)
OFFLINE CONTROL
VAI APPLICATION
CACHE!
Aformade cachear arquivos pareciasimples...
http://diveintohtml5.info/offline.html
APPCACHE IS A
DOUCHEBAG!
http://alistapart.com/article/application-cache-is-a-douchebag
http://sergiolopes.org/palestra-appcache-html5-offline
http://eduardomatos.me/appcache-manifest-e-serviceworker-
as-partes-boas-e-ruins
LÁ VEM O
SERVICEWORKERS
//mainscript
navigator.serviceWorker.register("/assets/worker.js").then(
function(serviceWorker){
serviceWorker.postMessage("ServiceWorkersinstaladocomsucesso.");
},
function(error){
console.error("Ops..nãorolouainstalaçãodoServiceWorkers",error);
});
Interceptando requests
//assets/worker.js
varbase="https://meu.server.com";
vardata_url=newURL("/data/posts.json",base)+"";
self.addEventListener("fetch",function(e){
varurl=e.request.url;
console.log(url);
if(url==data_url){
e.respondWith(
newResponse(JSON.stringify({
posts:{/*...*/}
}),{
headers:{'Content-Type':'application/json'},
status:200
})
);
}
});
Cacheando seus assets
//assets/worker.js
self.version=1;
varbase="https://meu.server.com"
//ListenerparaainstalaçãodoServiceWorkers
self.addEventListener("install",function(e){
varmyResources=newCache(
base+"/index.html",
base+"/assets/application.css",
base+"/assets/application.js",
base+"/assets/logo.png",
base+"/data/posts.json",
base+"/data/posts_fallback.json"
);
e.waitUntil(myResources.ready());
caches.set("caches-"+self.version,myResources);
});
Request+ Cache
//assets/worker.js
self.version=2;
varbase="https://meu.server.com"
vardata_url=newURL("/data/posts.json",base)+"";
self.addEventListener("fetch",
function(e){
if(e.request.url==data_url){
e.respondWith(
caches.match(e.request)
.catch(function(){
returne.default;
})
.catch(function(){
returncaches.match("/data/posts_fallback.json");
})
);
}
}
);
EXEMPLO DE
SERVICEWORKERS
https://jakearchibald.github.io/trained-to-thrill/
E A SEGURANÇA DISSO?
Funcionaapenas com https
Escopo por domains
BACKGROUND SYNC
Aindamuito recente
//mainscript
navigator.serviceWorker.register("/assets/worker.js");
navigator.serviceWorker.ready.then(function(sw){
//ReturnsaPromise
navigator.sync.register(
"my_data_sync",
{
minInterval:86400*1000, //ms,default:heuristic
repeating:true, //default:false
data:'', //default:emptystring
description:'', //default:emptystring
lang:'', //default:documentlang
dir:'' //default:documentdir
}
).then(function(){//Success
//Noresolvedvalue
//Success,syncisnowregistered
},
function(){//Failure
//IfnoSWregistration
//User/UAdeniedpermission
//Syncidalreadyregistered
});
});
//assets/worker.js
self.onsync=function(event){
vardata=JSON.parse(event.data);
if(event.id==="my_data_sync"){
if(data.whatever==="foo"){
//rejectionisindicationthattheUAshouldtry
//later(especiallywhennetworkisok)
event.waitUntil(doAsyncStuff());
}
}else{
//Garbagecollectunknownsyncs(perhapsfromolderpages).
navigator.sync.unregister(event.id);
}
};
GEOFENCING
Nem aspec foidefinida.
BLUETOOTH
Spec aindaengatinhando
https://github.com/WebBluetoothCG/web-bluetooth
http://www.w3.org/community/web-bluetooth
ONDE FUNCIONA?
https://jakearchibald.github.io/isserviceworkerready/
PORQUE ESSE HYPE
TODO?
JavaScriptchegando no app nativo
Evolução e maior controle das aplicações
Acesso afuncionalidades do sistemado usuário (bluetooth,
push notifications...)
OBRIGADO!
link dapalestra: bit.ly/serviceworkers-poa
meu twitter: @eduardojmatos
fontes: http://bit.ly/serviceworkers-links

Más contenido relacionado

Similar a Service Workers e o futuro das aplicações no seu browser

Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
wpnepal
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
The Power of the JVM: Applied Polyglot Projects with Java and JavaScript
The Power of the JVM: Applied Polyglot Projects with Java and JavaScriptThe Power of the JVM: Applied Polyglot Projects with Java and JavaScript
The Power of the JVM: Applied Polyglot Projects with Java and JavaScript
Hazelcast
 

Similar a Service Workers e o futuro das aplicações no seu browser (20)

Web Workers
Web WorkersWeb Workers
Web Workers
 
Unit testing @ WordPress Meetup Tilburg 7 januari 2014
Unit testing @ WordPress Meetup Tilburg 7 januari 2014Unit testing @ WordPress Meetup Tilburg 7 januari 2014
Unit testing @ WordPress Meetup Tilburg 7 januari 2014
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
 
JSChannel 2017 - Service Workers and the Role they Play in modern day web-apps
JSChannel 2017 - Service Workers and the Role they Play in modern day web-appsJSChannel 2017 - Service Workers and the Role they Play in modern day web-apps
JSChannel 2017 - Service Workers and the Role they Play in modern day web-apps
 
Programming proxies to do what we need so we don't have to talk to the networ...
Programming proxies to do what we need so we don't have to talk to the networ...Programming proxies to do what we need so we don't have to talk to the networ...
Programming proxies to do what we need so we don't have to talk to the networ...
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015
 
Unit Testing Express Middleware
Unit Testing Express MiddlewareUnit Testing Express Middleware
Unit Testing Express Middleware
 
WEB-VR by Ankitkumar Singh
WEB-VR by Ankitkumar SinghWEB-VR by Ankitkumar Singh
WEB-VR by Ankitkumar Singh
 
Mobile optimization
Mobile optimizationMobile optimization
Mobile optimization
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
jsDay 2016 recap
jsDay 2016 recapjsDay 2016 recap
jsDay 2016 recap
 
Ember: Guts & Goals
Ember: Guts & GoalsEmber: Guts & Goals
Ember: Guts & Goals
 
The Power of the JVM: Applied Polyglot Projects with Java and JavaScript
The Power of the JVM: Applied Polyglot Projects with Java and JavaScriptThe Power of the JVM: Applied Polyglot Projects with Java and JavaScript
The Power of the JVM: Applied Polyglot Projects with Java and JavaScript
 
Service worker - Offline Web
Service worker - Offline WebService worker - Offline Web
Service worker - Offline Web
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
"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 "
 
Build Web Apps using Node.js
Build Web Apps using Node.jsBuild Web Apps using Node.js
Build Web Apps using Node.js
 
Claim Academy Intro to Programming
Claim Academy Intro to ProgrammingClaim Academy Intro to Programming
Claim Academy Intro to Programming
 
Node js salesforce integration using js force a quick guide to look out in 20...
Node js salesforce integration using js force a quick guide to look out in 20...Node js salesforce integration using js force a quick guide to look out in 20...
Node js salesforce integration using js force a quick guide to look out in 20...
 

Último

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Último (20)

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 

Service Workers e o futuro das aplicações no seu browser