SlideShare une entreprise Scribd logo
1  sur  42
Télécharger pour lire hors ligne
Web improvements @robertnyman
Promises
fulfilled = The action relating to the promise succeeded
rejected = The action relating to the promise failed
pending = Hasn't fulfilled or rejected yet
settled = Has fulfilled or rejected
var promise = new Promise(function(resolve, reject) {

// do a thing, possibly async, then…



if (/* everything turned out fine */) {

resolve("Stuff worked!");

}

else {

reject(Error("It broke"));

}

});
promise.then(function(result) {

console.log(result); // "Stuff worked!"

}, function(err) {

console.log(err); // Error: "It broke"

});
fetch()
XMLHttpRequest example
function reqListener() { 

var data = JSON.parse(this.responseText); 

console.log(data); 

}



function reqError(err) { 

console.log('Fetch Error :-S', err); 

}



var oReq = new XMLHttpRequest(); 

oReq.onload = reqListener; 

oReq.onerror = reqError; 

oReq.open('get', './api/some.json', true); 

oReq.send();
fetch() version
fetch('./api/some.json') 

.then( 

function(response) { 

if (response.status !== 200) { 

console.log('Looks like there was a problem. Status Code: ' + 

response.status); 

return; 

}



// Examine the text in the response 

response.json().then(function(data) { 

console.log(data); 

}); 

} 

) 

.catch(function(err) { 

console.log('Fetch Error :-S', err); 

});
Response metadata
fetch('users.json').then(function(response) { 

console.log(response.headers.get('Content-Type')); 

console.log(response.headers.get('Date'));



console.log(response.status); 

console.log(response.statusText); 

console.log(response.type); 

console.log(response.url); 

});
Response Types
basic
cors
opaque
Defining modes
same-origin
cors
cors-with-forced-preflight
no-cors
Defining modes
fetch('http://some-site.com/cors-enabled/some.json', {mode: 'cors'}) 

.then(function(response) { 

return response.text(); 

}) 

.then(function(text) { 

console.log('Request successful', text); 

}) 

.catch(function(error) { 

log('Request failed', error) 

});
Service Workers
It's a JavaScript Worker, so it can't access the DOM
directly. Instead responds to postMessages
Service worker is a programmable network proxy
It will be terminated when not in use, and restarted
when it's next needed
Makes extensive use of Promises
No Service Worker
HTTPS is Needed
Register and Installing a Service Worker
if ('serviceWorker' in navigator) {

navigator.serviceWorker.register('/sw.js').then(function(registration) {

// Registration was successful

console.log('ServiceWorker registration successful with scope: ',
registration.scope);

}).catch(function(err) {

// registration failed :(

console.log('ServiceWorker registration failed: ', err);

});

}
chrome://inspect/#service-workers
// The files we want to cache

var urlsToCache = [

'/',

'/styles/main.css',

'/script/main.js'

];



// Set the callback for the install step

self.addEventListener('install', function(event) {

// Perform install steps

});
Installing
Inside our install callback:
1. Open a cache
2. Cache our files
3. Confirm whether all the required
assets are cached or not
Install callback
var CACHE_NAME = 'my-site-cache-v1';

var urlsToCache = [

'/',

'/styles/main.css',

'/script/main.js'

];



self.addEventListener('install', function(event) {

// Perform install steps

event.waitUntil(

caches.open(CACHE_NAME)

.then(function(cache) {

console.log('Opened cache');

return cache.addAll(urlsToCache);

})

);

});
self.addEventListener('fetch', function(event) {

event.respondWith(

caches.match(event.request)

.then(function(response) {

// Cache hit - return response

if (response) {

return response;

}



return fetch(event.request);

}

)

);

});
Caching and Returning Requests
self.addEventListener('fetch', function(event) {

event.respondWith(

caches.match(event.request)

.then(function(response) {

// Cache hit - return response

if (response) {

return response;

}



// IMPORTANT: Clone the request. A request is a stream and

// can only be consumed once. Since we are consuming this

// once by cache and once by the browser for fetch, we need

// to clone the response

var fetchRequest = event.request.clone();



return fetch(fetchRequest).then(

function(response) {

// Check if we received a valid response

if(!response || response.status !== 200 || response.type !== 'basic') {

return response;

}



// IMPORTANT: Clone the response. A response is a stream

// and because we want the browser to consume the response

// as well as the cache consuming the response, we need

// to clone it so we have 2 stream.

var responseToCache = response.clone();



caches.open(CACHE_NAME)

.then(function(cache) {

cache.put(event.request, responseToCache);

});



return response;

}

);

})

);

});
Caching new requests cumulatively
Updating a Service Worker
1. Update your service worker JavaScript file.
2. Your new service worker will be started and the
install event will be fired.
3. New Service Worker will enter a "waiting" state
4. When open pages are closed, the old Service
Worker will be killed - new service worker will take
control.
5. Once new Service Worker takes control, its
activate event will be fired.
Updating a Service Worker
Cache management & whitelists
self.addEventListener('activate', function(event) {



var cacheWhitelist = ['pages-cache-v1', 'blog-posts-cache-v1'];



event.waitUntil(

caches.keys().then(function(cacheNames) {

return Promise.all(

cacheNames.map(function(cacheName) {

if (cacheWhitelist.indexOf(cacheName) === -1) {

return caches.delete(cacheName);

}

})

);

})

);

});
Push notifications
<button class="js-push-button" disabled> 

Enable Push Messages 

</button>
// Are Notifications supported in the service worker? 

if (!('showNotification' in ServiceWorkerRegistration.prototype)) { 

console.warn('Notifications aren't supported.'); 

return; 

}
// Check the current Notification permission. 

// If its denied, it's a permanent block until the 

// user changes the permission 

if (Notification.permission === 'denied') { 

console.warn('The user has blocked notifications.'); 

return; 

}
// Check if push messaging is supported 

if (!('PushManager' in window)) { 

console.warn('Push messaging isn't supported.'); 

return; 

}
// We need the service worker registration to check for a subscription 

navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { 

// Do we already have a push message subscription? 

serviceWorkerRegistration.pushManager.getSubscription() 

.then(function(subscription) { 

// Enable any UI which subscribes / unsubscribes from 

// push messages. 

var pushButton = document.querySelector('.js-push-button'); 

pushButton.disabled = false;



if (!subscription) { 

// We aren't subscribed to push, so set UI 

// to allow the user to enable push 

return; 

}



// Keep your server in sync with the latest subscriptionId

sendSubscriptionToServer(subscription);



// Set your UI to show they have subscribed for 

// push messages 

pushButton.textContent = 'Disable Push Messages'; 

isPushEnabled = true; 

}) 

.catch(function(err) { 

console.warn('Error during getSubscription()', err); 

}); 

});
{ 

"name": "Push Demo", 

"short_name": "Push Demo", 

"icons": [{ 

"src": "images/icon-192x192.png", 

"sizes": "192x192",

"type": "image/png" 

}], 

"start_url": "/index.html?homescreen=1", 

"display": "standalone", 

"gcm_sender_id": "123456789012", 

"gcm_user_visible_only": true 

}
<link rel="manifest" href="manifest.json">
Add to
Homescreen
Cache management & whitelistsApp Install Banners
App Install Banners prerequisites
You have a web app manifest file
You have a service worker registered on
your site. We recommend a simple custom
offline page service worker
Your site is served over HTTPS (you need a
service worker after all)
The user has visited your site twice over
two separate days during the course of two
weeks.
"You can do all of this?"
Robert Nyman
robertnyman.com

rnyman@google.com

Google
@robertnyman

Contenu connexe

Tendances

Converter suhu
Converter suhuConverter suhu
Converter suhu
Bayu Bakti
 

Tendances (20)

React lecture
React lectureReact lecture
React lecture
 
Ember and containers
Ember and containersEmber and containers
Ember and containers
 
Introduction to React & Redux
Introduction to React & ReduxIntroduction to React & Redux
Introduction to React & Redux
 
Complex Architectures in Ember
Complex Architectures in EmberComplex Architectures in Ember
Complex Architectures in Ember
 
Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2Quick start with React | DreamLab Academy #2
Quick start with React | DreamLab Academy #2
 
React + Redux. Best practices
React + Redux.  Best practicesReact + Redux.  Best practices
React + Redux. Best practices
 
Switch to React.js from AngularJS developer
Switch to React.js from AngularJS developerSwitch to React.js from AngularJS developer
Switch to React.js from AngularJS developer
 
ASP.NET MVC Internals
ASP.NET MVC InternalsASP.NET MVC Internals
ASP.NET MVC Internals
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3
 
Reliable Javascript
Reliable Javascript Reliable Javascript
Reliable Javascript
 
Redux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with AsyncRedux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with Async
 
Converter suhu
Converter suhuConverter suhu
Converter suhu
 
Angular server-side communication
Angular server-side communicationAngular server-side communication
Angular server-side communication
 
Redux training
Redux trainingRedux training
Redux training
 
Getting started with ReactJS
Getting started with ReactJSGetting started with ReactJS
Getting started with ReactJS
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기
 
React и redux
React и reduxReact и redux
React и redux
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with Redux
 
Service workers and the role they play in modern day web apps
Service workers and the role they play in modern day web appsService workers and the role they play in modern day web apps
Service workers and the role they play in modern day web apps
 

Similaire à New improvements for web developers - frontend.fi, Helsinki

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
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao PauloJavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
Robert Nyman
 

Similaire à New improvements for web developers - frontend.fi, Helsinki (20)

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
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
PWA 與 Service Worker
PWA 與 Service WorkerPWA 與 Service Worker
PWA 與 Service Worker
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
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
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !
 
Service Worker - Reliability bits
Service Worker - Reliability bitsService Worker - Reliability bits
Service Worker - Reliability bits
 
Introduction to Service Workers | Matteo Manchi
Introduction to Service Workers | Matteo ManchiIntroduction to Service Workers | Matteo Manchi
Introduction to Service Workers | Matteo Manchi
 
You promise?
You promise?You promise?
You promise?
 
Promises, promises, and then observables
Promises, promises, and then observablesPromises, promises, and then observables
Promises, promises, and then observables
 
Offline First with Service Worker
Offline First with Service WorkerOffline First with Service Worker
Offline First with Service Worker
 
Workboxで始める Service Worker
Workboxで始める Service WorkerWorkboxで始める Service Worker
Workboxで始める Service Worker
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Service workers
Service workersService workers
Service workers
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao PauloJavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
 
Nevyn — Promise, It's Async! Swift Language User Group Lightning Talk 2015-09-24
Nevyn — Promise, It's Async! Swift Language User Group Lightning Talk 2015-09-24Nevyn — Promise, It's Async! Swift Language User Group Lightning Talk 2015-09-24
Nevyn — Promise, It's Async! Swift Language User Group Lightning Talk 2015-09-24
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS Services
 
MeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenmentMeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenment
 

Plus de Robert Nyman

Plus de Robert Nyman (20)

Have you tried listening?
Have you tried listening?Have you tried listening?
Have you tried listening?
 
Building for Your Next Billion - Google I/O 2017
Building for Your Next Billion - Google I/O 2017Building for Your Next Billion - Google I/O 2017
Building for Your Next Billion - Google I/O 2017
 
Introduction to Google Daydream
Introduction to Google DaydreamIntroduction to Google Daydream
Introduction to Google Daydream
 
Predictability for the Web
Predictability for the WebPredictability for the Web
Predictability for the Web
 
The Future of Progressive Web Apps - View Source conference, Berlin 2016
The Future of Progressive Web Apps - View Source conference, Berlin 2016The Future of Progressive Web Apps - View Source conference, Berlin 2016
The Future of Progressive Web Apps - View Source conference, Berlin 2016
 
The Future of the Web - Cold Front conference 2016
The Future of the Web - Cold Front conference 2016The Future of the Web - Cold Front conference 2016
The Future of the Web - Cold Front conference 2016
 
The Future of Progressive Web Apps - Google for Indonesia
The Future of Progressive Web Apps - Google for IndonesiaThe Future of Progressive Web Apps - Google for Indonesia
The Future of Progressive Web Apps - Google for Indonesia
 
Google tech & products
Google tech & productsGoogle tech & products
Google tech & products
 
Introduction to Progressive Web Apps, Google Developer Summit, Seoul - South ...
Introduction to Progressive Web Apps, Google Developer Summit, Seoul - South ...Introduction to Progressive Web Apps, Google Developer Summit, Seoul - South ...
Introduction to Progressive Web Apps, Google Developer Summit, Seoul - South ...
 
Progressive Web Apps keynote, Google Developer Summit, Tokyo, Japan
Progressive Web Apps keynote, Google Developer Summit, Tokyo, JapanProgressive Web Apps keynote, Google Developer Summit, Tokyo, Japan
Progressive Web Apps keynote, Google Developer Summit, Tokyo, Japan
 
The web - What it has, what it lacks and where it must go - keynote at Riga D...
The web - What it has, what it lacks and where it must go - keynote at Riga D...The web - What it has, what it lacks and where it must go - keynote at Riga D...
The web - What it has, what it lacks and where it must go - keynote at Riga D...
 
The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...
The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...
The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...
 
The web - What it has, what it lacks and where it must go - Istanbul
The web - What it has, what it lacks and where it must go - IstanbulThe web - What it has, what it lacks and where it must go - Istanbul
The web - What it has, what it lacks and where it must go - Istanbul
 
The web - What it has, what it lacks and where it must go
The web - What it has, what it lacks and where it must goThe web - What it has, what it lacks and where it must go
The web - What it has, what it lacks and where it must go
 
Google, the future and possibilities
Google, the future and possibilitiesGoogle, the future and possibilities
Google, the future and possibilities
 
Developer Relations in the Nordics
Developer Relations in the NordicsDeveloper Relations in the Nordics
Developer Relations in the Nordics
 
What is Developer Relations?
What is Developer Relations?What is Developer Relations?
What is Developer Relations?
 
Android TV Introduction - Stockholm Android TV meetup
Android TV Introduction - Stockholm Android TV meetupAndroid TV Introduction - Stockholm Android TV meetup
Android TV Introduction - Stockholm Android TV meetup
 
Mobile phone trends, user data & developer climate - frontend.fi, Helsinki
Mobile phone trends, user data & developer climate - frontend.fi, HelsinkiMobile phone trends, user data & developer climate - frontend.fi, Helsinki
Mobile phone trends, user data & developer climate - frontend.fi, Helsinki
 
Google & gaming, IGDA - Helsinki
Google & gaming, IGDA - HelsinkiGoogle & gaming, IGDA - Helsinki
Google & gaming, IGDA - Helsinki
 

Dernier

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Dernier (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 

New improvements for web developers - frontend.fi, Helsinki

  • 3.
  • 4. fulfilled = The action relating to the promise succeeded rejected = The action relating to the promise failed pending = Hasn't fulfilled or rejected yet settled = Has fulfilled or rejected
  • 5. var promise = new Promise(function(resolve, reject) {
 // do a thing, possibly async, then…
 
 if (/* everything turned out fine */) {
 resolve("Stuff worked!");
 }
 else {
 reject(Error("It broke"));
 }
 });
  • 6. promise.then(function(result) {
 console.log(result); // "Stuff worked!"
 }, function(err) {
 console.log(err); // Error: "It broke"
 });
  • 8. XMLHttpRequest example function reqListener() { 
 var data = JSON.parse(this.responseText); 
 console.log(data); 
 }
 
 function reqError(err) { 
 console.log('Fetch Error :-S', err); 
 }
 
 var oReq = new XMLHttpRequest(); 
 oReq.onload = reqListener; 
 oReq.onerror = reqError; 
 oReq.open('get', './api/some.json', true); 
 oReq.send();
  • 9. fetch() version fetch('./api/some.json') 
 .then( 
 function(response) { 
 if (response.status !== 200) { 
 console.log('Looks like there was a problem. Status Code: ' + 
 response.status); 
 return; 
 }
 
 // Examine the text in the response 
 response.json().then(function(data) { 
 console.log(data); 
 }); 
 } 
 ) 
 .catch(function(err) { 
 console.log('Fetch Error :-S', err); 
 });
  • 10. Response metadata fetch('users.json').then(function(response) { 
 console.log(response.headers.get('Content-Type')); 
 console.log(response.headers.get('Date'));
 
 console.log(response.status); 
 console.log(response.statusText); 
 console.log(response.type); 
 console.log(response.url); 
 });
  • 13. Defining modes fetch('http://some-site.com/cors-enabled/some.json', {mode: 'cors'}) 
 .then(function(response) { 
 return response.text(); 
 }) 
 .then(function(text) { 
 console.log('Request successful', text); 
 }) 
 .catch(function(error) { 
 log('Request failed', error) 
 });
  • 15. It's a JavaScript Worker, so it can't access the DOM directly. Instead responds to postMessages Service worker is a programmable network proxy It will be terminated when not in use, and restarted when it's next needed Makes extensive use of Promises
  • 16.
  • 19. Register and Installing a Service Worker if ('serviceWorker' in navigator) {
 navigator.serviceWorker.register('/sw.js').then(function(registration) {
 // Registration was successful
 console.log('ServiceWorker registration successful with scope: ', registration.scope);
 }).catch(function(err) {
 // registration failed :(
 console.log('ServiceWorker registration failed: ', err);
 });
 }
  • 21. // The files we want to cache
 var urlsToCache = [
 '/',
 '/styles/main.css',
 '/script/main.js'
 ];
 
 // Set the callback for the install step
 self.addEventListener('install', function(event) {
 // Perform install steps
 }); Installing
  • 22. Inside our install callback: 1. Open a cache 2. Cache our files 3. Confirm whether all the required assets are cached or not
  • 23. Install callback var CACHE_NAME = 'my-site-cache-v1';
 var urlsToCache = [
 '/',
 '/styles/main.css',
 '/script/main.js'
 ];
 
 self.addEventListener('install', function(event) {
 // Perform install steps
 event.waitUntil(
 caches.open(CACHE_NAME)
 .then(function(cache) {
 console.log('Opened cache');
 return cache.addAll(urlsToCache);
 })
 );
 });
  • 24. self.addEventListener('fetch', function(event) {
 event.respondWith(
 caches.match(event.request)
 .then(function(response) {
 // Cache hit - return response
 if (response) {
 return response;
 }
 
 return fetch(event.request);
 }
 )
 );
 }); Caching and Returning Requests
  • 25. self.addEventListener('fetch', function(event) {
 event.respondWith(
 caches.match(event.request)
 .then(function(response) {
 // Cache hit - return response
 if (response) {
 return response;
 }
 
 // IMPORTANT: Clone the request. A request is a stream and
 // can only be consumed once. Since we are consuming this
 // once by cache and once by the browser for fetch, we need
 // to clone the response
 var fetchRequest = event.request.clone();
 
 return fetch(fetchRequest).then(
 function(response) {
 // Check if we received a valid response
 if(!response || response.status !== 200 || response.type !== 'basic') {
 return response;
 }
 
 // IMPORTANT: Clone the response. A response is a stream
 // and because we want the browser to consume the response
 // as well as the cache consuming the response, we need
 // to clone it so we have 2 stream.
 var responseToCache = response.clone();
 
 caches.open(CACHE_NAME)
 .then(function(cache) {
 cache.put(event.request, responseToCache);
 });
 
 return response;
 }
 );
 })
 );
 }); Caching new requests cumulatively
  • 27. 1. Update your service worker JavaScript file. 2. Your new service worker will be started and the install event will be fired. 3. New Service Worker will enter a "waiting" state 4. When open pages are closed, the old Service Worker will be killed - new service worker will take control. 5. Once new Service Worker takes control, its activate event will be fired. Updating a Service Worker
  • 28. Cache management & whitelists self.addEventListener('activate', function(event) {
 
 var cacheWhitelist = ['pages-cache-v1', 'blog-posts-cache-v1'];
 
 event.waitUntil(
 caches.keys().then(function(cacheNames) {
 return Promise.all(
 cacheNames.map(function(cacheName) {
 if (cacheWhitelist.indexOf(cacheName) === -1) {
 return caches.delete(cacheName);
 }
 })
 );
 })
 );
 });
  • 30.
  • 31. <button class="js-push-button" disabled> 
 Enable Push Messages 
 </button>
  • 32. // Are Notifications supported in the service worker? 
 if (!('showNotification' in ServiceWorkerRegistration.prototype)) { 
 console.warn('Notifications aren't supported.'); 
 return; 
 }
  • 33. // Check the current Notification permission. 
 // If its denied, it's a permanent block until the 
 // user changes the permission 
 if (Notification.permission === 'denied') { 
 console.warn('The user has blocked notifications.'); 
 return; 
 }
  • 34. // Check if push messaging is supported 
 if (!('PushManager' in window)) { 
 console.warn('Push messaging isn't supported.'); 
 return; 
 }
  • 35. // We need the service worker registration to check for a subscription 
 navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) { 
 // Do we already have a push message subscription? 
 serviceWorkerRegistration.pushManager.getSubscription() 
 .then(function(subscription) { 
 // Enable any UI which subscribes / unsubscribes from 
 // push messages. 
 var pushButton = document.querySelector('.js-push-button'); 
 pushButton.disabled = false;
 
 if (!subscription) { 
 // We aren't subscribed to push, so set UI 
 // to allow the user to enable push 
 return; 
 }
 
 // Keep your server in sync with the latest subscriptionId
 sendSubscriptionToServer(subscription);
 
 // Set your UI to show they have subscribed for 
 // push messages 
 pushButton.textContent = 'Disable Push Messages'; 
 isPushEnabled = true; 
 }) 
 .catch(function(err) { 
 console.warn('Error during getSubscription()', err); 
 }); 
 });
  • 36. { 
 "name": "Push Demo", 
 "short_name": "Push Demo", 
 "icons": [{ 
 "src": "images/icon-192x192.png", 
 "sizes": "192x192",
 "type": "image/png" 
 }], 
 "start_url": "/index.html?homescreen=1", 
 "display": "standalone", 
 "gcm_sender_id": "123456789012", 
 "gcm_user_visible_only": true 
 } <link rel="manifest" href="manifest.json">
  • 38. Cache management & whitelistsApp Install Banners
  • 39. App Install Banners prerequisites You have a web app manifest file You have a service worker registered on your site. We recommend a simple custom offline page service worker Your site is served over HTTPS (you need a service worker after all) The user has visited your site twice over two separate days during the course of two weeks.
  • 40. "You can do all of this?"
  • 41.