SlideShare una empresa de Scribd logo
1 de 19
Descargar para leer sin conexión
SERVICE WORKER
OFFLINE-WEB WITH
BRUNOOSILVA
APP CACHE
BEFORE…
APP CACHE
ADVANTAGES
▸ Simple configuration
▸ Work in all browsers (up to IE)
▸ Quick to implement
APP CACHE
HTML
1 <html manifest="hello.appcache">
HELLO.APPCACHE
1 /index.html
2 /pagina-2.html
3 /nao-disponivel.html
4 /style.css
5 /app.js
6 /burro.jpg
7
8 NETWORK:
9 http://www.google-analytics.com/ga.js
10
11 FALLBACK:
12 /burro.jpg /sem-foto.jpg
APP CACHE
DISADVANTAGES
▸ Forget any url
▸ Set mime-type in server
▸ Nothing can give error 404 and 500
▸ No cache the manifest file (Danger)
▸ Impossible develop or debug
▸ etc …
APP CACHE
IS LIMITED
IS COMPLICATE
IS BORING
SERVICE WORKER
NOW
SERVICE WORKER
WHATS IS ?
▸ Service workers essentially act as proxy servers that sit
between web applications, and the browser and network
(when available). They are intended to (amongst other
things) enable the creation of effective offline experiences,
intercepting network requests and taking appropriate
action based on whether the network is available and
updated assets reside on the server. They will also allow
access to push notifications and background sync APIs.
SERVICE WORKER
INITIALIZATION
1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <script>
5 if ('serviceWorker' in navigator) {
6 navigator.serviceWorker.register('magica.js')
7 .then(function(){
8 console.log('Tem Service Worker! :)');
9 }, function(err){
10 console.log('Deu ruim! :(', err);
11 });
12 } else {
13 console.error('Use um browser melhor. :)');
14 }
15 </script>
16 </head>
17 <body>
18 <h1>Service Worker</h1>
19 </body>
20 </html>
SERVICE WORKER
MAGICA.JS - INSTALL
1 var path = '/',
2 CACHE_NAME = 'bluesoft-v1';
3
4 this.addEventListener('install', function(event) {
5 // Instala app, adicionar os arquivos no cache
6
7 event.waitUntil(
8 caches.open(CACHE_NAME).then(function(cache) {
9 return cache.addAll([
10 path,
11 path + 'index.html',
12 path + 'pagina-2.html',
13 path + 'nao-disponivel.html',
14 path + 'style.css',
15 path + 'app.js',
16 path + 'burro.jpg'
17 ]);
18 })
19 );
20 });
SERVICE WORKER
MAGICA.JS - FETCH
1 this.addEventListener('fetch', function(event) {
2 var response;
3 event.respondWith(caches.match(event.request)
4 .then(function(r) {
5 response = r;
6 if(!response){
7 throw "Nao tem no cache";
8 }
9 caches.open(CACHE_NAME).then(function(cache) {
10 cache.put(event.request, response);
11 });
12 return response.clone();
13 }).catch(function() {
14 return fetch(event.request).then(function(res){
15 return res.clone();
16 }, function(err){
17 return caches.match(path + 'nao-disponivel.html');
18 });
19 })
20 );
21 });
SERVICE WORKER
MAGICA.JS - UPDATE WITH INSTALL AND ACTIVATE
1 this.addEventListener('install', function(event) {
2 // Instala app, adicionar os arquivos no cache
3
4 event.waitUntil(
5 caches.open('bluesoft-v2').then(function(cache) {
6 return cache.addAll([
7 path,
8 path + 'index.html',
9 path + 'new-file.html'
10 ]);
11 })
12 );
13 });
14
15 this.addEventListener('activate', function(event) {
16 // App active and working
17
18 event.waitUntil(
19 caches.delete('bluesoft-v1')
20 );
21 });
SERVICE WORKER
ADVANTAGES
▸ Run in background ( with Browser closed )
▸ Based in promise
▸ Cache API
▸ Programmatic and controllable
▸ Chrome like ( Updates )
▸ The future
▸ etc …
SERVICE WORKER
DISADVANTAGES, BUT FOR SECURITY
▸ HTTPS only
▸ All asynchronous
▸ Not working localStorage (IndexDb only)
▸ Ajax synchronous
▸ Stop at any time
SERVICE WORKER
IDEAS FANTASTIC
BACKGROUND SYNC
1 registration.sync.register('event');
2 this.onsync = function(){}
PUSH NOTIFICATION
1 registration.pushRegistrationManager.register()
2 .then(function(details){ });
3
4 this.onpush = function(event){
5 new Notification(event.menssage.data);
6 };
7
8 this.onnotificationclick = function(){
9 new ServiceWorkerClient('/index.html')
10 };
GEOFENCING ALARM AND MUCH MORE…
SERVICE WORKER
WORK WITH
BY CANIUSE.COM
SERVICE WORKER
EDITORS
SERVICE WORKER
REFERENCES
▸ https://developer.mozilla.org/en-US/docs/Web/API/
Service_Worker_API
▸ https://www.w3.org/TR/service-workers/
▸ http://caniuse.com/#search=serviceWorker
▸ https://github.com/brunoosilva/service-worker
THANKS
BRUNOOSILVA

Más contenido relacionado

La actualidad más candente

The Peanut Butter Cup of Web-dev: Plack and single page web apps
The Peanut Butter Cup of Web-dev: Plack and single page web appsThe Peanut Butter Cup of Web-dev: Plack and single page web apps
The Peanut Butter Cup of Web-dev: Plack and single page web apps
John Anderson
 

La actualidad más candente (20)

Real World Lessons in Progressive Web Application & Service Worker Caching
Real World Lessons in Progressive Web Application & Service Worker CachingReal World Lessons in Progressive Web Application & Service Worker Caching
Real World Lessons in Progressive Web Application & Service Worker Caching
 
PWA 應用 - 實現網站離線瀏覽
PWA 應用 - 實現網站離線瀏覽PWA 應用 - 實現網站離線瀏覽
PWA 應用 - 實現網站離線瀏覽
 
Building a js widget
Building a js widgetBuilding a js widget
Building a js widget
 
Testing frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabsTesting frontends with nightwatch & saucelabs
Testing frontends with nightwatch & saucelabs
 
ServiceWorker: New game changer is coming!
ServiceWorker: New game changer is coming!ServiceWorker: New game changer is coming!
ServiceWorker: New game changer is coming!
 
JQuery UK Service Workers Talk
JQuery UK Service Workers TalkJQuery UK Service Workers Talk
JQuery UK Service Workers Talk
 
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
 
The Peanut Butter Cup of Web-dev: Plack and single page web apps
The Peanut Butter Cup of Web-dev: Plack and single page web appsThe Peanut Butter Cup of Web-dev: Plack and single page web apps
The Peanut Butter Cup of Web-dev: Plack and single page web apps
 
Introduction to AJAX In WordPress
Introduction to AJAX In WordPressIntroduction to AJAX In WordPress
Introduction to AJAX In WordPress
 
Thomas Fuchs Presentation
Thomas Fuchs PresentationThomas Fuchs Presentation
Thomas Fuchs Presentation
 
"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 "
 
Service worker: discover the next web game changer
Service worker: discover the next web game changerService worker: discover the next web game changer
Service worker: discover the next web game changer
 
Packing it all: JavaScript module bundling from 2000 to now
Packing it all: JavaScript module bundling from 2000 to nowPacking it all: JavaScript module bundling from 2000 to now
Packing it all: JavaScript module bundling from 2000 to now
 
20160905 - BrisJS - nightwatch testing
20160905 - BrisJS - nightwatch testing20160905 - BrisJS - nightwatch testing
20160905 - BrisJS - nightwatch testing
 
iPhone Appleless Apps
iPhone Appleless AppsiPhone Appleless Apps
iPhone Appleless Apps
 
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
 
Building a Startup Stack with AngularJS
Building a Startup Stack with AngularJSBuilding a Startup Stack with AngularJS
Building a Startup Stack with AngularJS
 
Svelte JS introduction
Svelte JS introductionSvelte JS introduction
Svelte JS introduction
 
REST to JavaScript for Better Client-side Development
REST to JavaScript for Better Client-side DevelopmentREST to JavaScript for Better Client-side Development
REST to JavaScript for Better Client-side Development
 
Nodejs.meetup
Nodejs.meetupNodejs.meetup
Nodejs.meetup
 

Destacado

A Validation Model of Data Input for Web Services
A Validation Model of Data Input for Web ServicesA Validation Model of Data Input for Web Services
A Validation Model of Data Input for Web Services
Rafael Brinhosa
 

Destacado (8)

Progressive Web Apps: o melhor da Web appficada
Progressive Web Apps: o melhor da Web appficadaProgressive Web Apps: o melhor da Web appficada
Progressive Web Apps: o melhor da Web appficada
 
Offline Web com Service Workers - Sérgio Lopes
Offline Web com Service Workers - Sérgio LopesOffline Web com Service Workers - Sérgio Lopes
Offline Web com Service Workers - Sérgio Lopes
 
Progressive Web Apps e o futuro do desenvolvimento Web na Plataforma .NET
Progressive Web Apps e o futuro do desenvolvimento Web na Plataforma .NETProgressive Web Apps e o futuro do desenvolvimento Web na Plataforma .NET
Progressive Web Apps e o futuro do desenvolvimento Web na Plataforma .NET
 
A Validation Model of Data Input for Web Services
A Validation Model of Data Input for Web ServicesA Validation Model of Data Input for Web Services
A Validation Model of Data Input for Web Services
 
Progressive Web Apps
Progressive Web AppsProgressive Web Apps
Progressive Web Apps
 
Boas práticas de API Design
Boas práticas de API DesignBoas práticas de API Design
Boas práticas de API Design
 
Material design para web
Material design para webMaterial design para web
Material design para web
 
ASP .NET CORE, Angular 2, e Typescript com Scaffolding Yeoman | Seminário
ASP .NET CORE, Angular 2, e Typescript com Scaffolding Yeoman  | Seminário ASP .NET CORE, Angular 2, e Typescript com Scaffolding Yeoman  | Seminário
ASP .NET CORE, Angular 2, e Typescript com Scaffolding Yeoman | Seminário
 

Similar a Service worker - Offline Web

WebAPIs & WebRTC - Spotify/sthlm.js
WebAPIs & WebRTC - Spotify/sthlm.jsWebAPIs & WebRTC - Spotify/sthlm.js
WebAPIs & WebRTC - Spotify/sthlm.js
Robert Nyman
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
Ben Lin
 
Functional Web Development
Functional Web DevelopmentFunctional Web Development
Functional Web Development
FITC
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
Alex Su
 
BlackBerry DevCon 2011 - PhoneGap and WebWorks
BlackBerry DevCon 2011 - PhoneGap and WebWorksBlackBerry DevCon 2011 - PhoneGap and WebWorks
BlackBerry DevCon 2011 - PhoneGap and WebWorks
mwbrooks
 
Web APIs & Apps - Mozilla
Web APIs & Apps - MozillaWeb APIs & Apps - Mozilla
Web APIs & Apps - Mozilla
Robert Nyman
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
wpnepal
 
Bringing the open web and APIs to mobile devices with Firefox OS - Whisky W...
 	Bringing the open web and APIs to mobile devices with Firefox OS - Whisky W... 	Bringing the open web and APIs to mobile devices with Firefox OS - Whisky W...
Bringing the open web and APIs to mobile devices with Firefox OS - Whisky W...
Robert Nyman
 

Similar a Service worker - Offline Web (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
 
WebAPIs & WebRTC - Spotify/sthlm.js
WebAPIs & WebRTC - Spotify/sthlm.jsWebAPIs & WebRTC - Spotify/sthlm.js
WebAPIs & WebRTC - Spotify/sthlm.js
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
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
 
Django + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar DjangoDjango + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar Django
 
Quick and Easy Development with Node.js and Couchbase Server
Quick and Easy Development with Node.js and Couchbase ServerQuick and Easy Development with Node.js and Couchbase Server
Quick and Easy Development with Node.js and Couchbase Server
 
Asynchronous Interfaces
Asynchronous InterfacesAsynchronous Interfaces
Asynchronous Interfaces
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
Mozilla Web Apps - Super-VanJS
Mozilla Web Apps - Super-VanJSMozilla Web Apps - Super-VanJS
Mozilla Web Apps - Super-VanJS
 
Functional Web Development
Functional Web DevelopmentFunctional Web Development
Functional Web Development
 
Progressive What Apps?
Progressive What Apps?Progressive What Apps?
Progressive What Apps?
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
 
BlackBerry DevCon 2011 - PhoneGap and WebWorks
BlackBerry DevCon 2011 - PhoneGap and WebWorksBlackBerry DevCon 2011 - PhoneGap and WebWorks
BlackBerry DevCon 2011 - PhoneGap and WebWorks
 
Web APIs & Apps - Mozilla
Web APIs & Apps - MozillaWeb APIs & Apps - Mozilla
Web APIs & Apps - Mozilla
 
Express Presentation
Express PresentationExpress Presentation
Express Presentation
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
 
Bringing the open web and APIs to mobile devices with Firefox OS - Whisky W...
 	Bringing the open web and APIs to mobile devices with Firefox OS - Whisky W... 	Bringing the open web and APIs to mobile devices with Firefox OS - Whisky W...
Bringing the open web and APIs to mobile devices with Firefox OS - Whisky W...
 
Reliable Javascript
Reliable Javascript Reliable Javascript
Reliable Javascript
 

Último

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 

Último (20)

Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
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-...
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 

Service worker - Offline Web

  • 3. APP CACHE ADVANTAGES ▸ Simple configuration ▸ Work in all browsers (up to IE) ▸ Quick to implement
  • 4. APP CACHE HTML 1 <html manifest="hello.appcache"> HELLO.APPCACHE 1 /index.html 2 /pagina-2.html 3 /nao-disponivel.html 4 /style.css 5 /app.js 6 /burro.jpg 7 8 NETWORK: 9 http://www.google-analytics.com/ga.js 10 11 FALLBACK: 12 /burro.jpg /sem-foto.jpg
  • 5. APP CACHE DISADVANTAGES ▸ Forget any url ▸ Set mime-type in server ▸ Nothing can give error 404 and 500 ▸ No cache the manifest file (Danger) ▸ Impossible develop or debug ▸ etc …
  • 6. APP CACHE IS LIMITED IS COMPLICATE IS BORING
  • 8. SERVICE WORKER WHATS IS ? ▸ Service workers essentially act as proxy servers that sit between web applications, and the browser and network (when available). They are intended to (amongst other things) enable the creation of effective offline experiences, intercepting network requests and taking appropriate action based on whether the network is available and updated assets reside on the server. They will also allow access to push notifications and background sync APIs.
  • 9. SERVICE WORKER INITIALIZATION 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <script> 5 if ('serviceWorker' in navigator) { 6 navigator.serviceWorker.register('magica.js') 7 .then(function(){ 8 console.log('Tem Service Worker! :)'); 9 }, function(err){ 10 console.log('Deu ruim! :(', err); 11 }); 12 } else { 13 console.error('Use um browser melhor. :)'); 14 } 15 </script> 16 </head> 17 <body> 18 <h1>Service Worker</h1> 19 </body> 20 </html>
  • 10. SERVICE WORKER MAGICA.JS - INSTALL 1 var path = '/', 2 CACHE_NAME = 'bluesoft-v1'; 3 4 this.addEventListener('install', function(event) { 5 // Instala app, adicionar os arquivos no cache 6 7 event.waitUntil( 8 caches.open(CACHE_NAME).then(function(cache) { 9 return cache.addAll([ 10 path, 11 path + 'index.html', 12 path + 'pagina-2.html', 13 path + 'nao-disponivel.html', 14 path + 'style.css', 15 path + 'app.js', 16 path + 'burro.jpg' 17 ]); 18 }) 19 ); 20 });
  • 11. SERVICE WORKER MAGICA.JS - FETCH 1 this.addEventListener('fetch', function(event) { 2 var response; 3 event.respondWith(caches.match(event.request) 4 .then(function(r) { 5 response = r; 6 if(!response){ 7 throw "Nao tem no cache"; 8 } 9 caches.open(CACHE_NAME).then(function(cache) { 10 cache.put(event.request, response); 11 }); 12 return response.clone(); 13 }).catch(function() { 14 return fetch(event.request).then(function(res){ 15 return res.clone(); 16 }, function(err){ 17 return caches.match(path + 'nao-disponivel.html'); 18 }); 19 }) 20 ); 21 });
  • 12. SERVICE WORKER MAGICA.JS - UPDATE WITH INSTALL AND ACTIVATE 1 this.addEventListener('install', function(event) { 2 // Instala app, adicionar os arquivos no cache 3 4 event.waitUntil( 5 caches.open('bluesoft-v2').then(function(cache) { 6 return cache.addAll([ 7 path, 8 path + 'index.html', 9 path + 'new-file.html' 10 ]); 11 }) 12 ); 13 }); 14 15 this.addEventListener('activate', function(event) { 16 // App active and working 17 18 event.waitUntil( 19 caches.delete('bluesoft-v1') 20 ); 21 });
  • 13. SERVICE WORKER ADVANTAGES ▸ Run in background ( with Browser closed ) ▸ Based in promise ▸ Cache API ▸ Programmatic and controllable ▸ Chrome like ( Updates ) ▸ The future ▸ etc …
  • 14. SERVICE WORKER DISADVANTAGES, BUT FOR SECURITY ▸ HTTPS only ▸ All asynchronous ▸ Not working localStorage (IndexDb only) ▸ Ajax synchronous ▸ Stop at any time
  • 15. SERVICE WORKER IDEAS FANTASTIC BACKGROUND SYNC 1 registration.sync.register('event'); 2 this.onsync = function(){} PUSH NOTIFICATION 1 registration.pushRegistrationManager.register() 2 .then(function(details){ }); 3 4 this.onpush = function(event){ 5 new Notification(event.menssage.data); 6 }; 7 8 this.onnotificationclick = function(){ 9 new ServiceWorkerClient('/index.html') 10 }; GEOFENCING ALARM AND MUCH MORE…
  • 18. SERVICE WORKER REFERENCES ▸ https://developer.mozilla.org/en-US/docs/Web/API/ Service_Worker_API ▸ https://www.w3.org/TR/service-workers/ ▸ http://caniuse.com/#search=serviceWorker ▸ https://github.com/brunoosilva/service-worker