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

Contenu connexe

Tendances

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
 

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

En vedette

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
 

En vedette (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
 

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

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

Dernier

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 

Dernier (20)

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...
 
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
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
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
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
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
 
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
 
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-...
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
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
 
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 🔝✔️✔️
 
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
 
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
 

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