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

Ember and containers
Ember and containersEmber and containers
Ember and containersMatthew Beale
 
Introduction to React & Redux
Introduction to React & ReduxIntroduction to React & Redux
Introduction to React & ReduxBoris Dinkevich
 
Complex Architectures in Ember
Complex Architectures in EmberComplex Architectures in Ember
Complex Architectures in EmberMatthew Beale
 
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 #2DreamLab
 
React + Redux. Best practices
React + Redux.  Best practicesReact + Redux.  Best practices
React + Redux. Best practicesClickky
 
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 developerEugene Zharkov
 
ASP.NET MVC Internals
ASP.NET MVC InternalsASP.NET MVC Internals
ASP.NET MVC InternalsVitaly Baum
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 DreamLab
 
Reliable Javascript
Reliable Javascript Reliable Javascript
Reliable Javascript Glenn Stovall
 
Redux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with AsyncRedux Thunk - Fu - Fighting with Async
Redux Thunk - Fu - Fighting with AsyncArtur Szott
 
Converter suhu
Converter suhuConverter suhu
Converter suhuBayu Bakti
 
Angular server-side communication
Angular server-side communicationAngular server-side communication
Angular server-side communicationAlexe Bogdan
 
Redux training
Redux trainingRedux training
Redux trainingdasersoft
 
Getting started with ReactJS
Getting started with ReactJSGetting started with ReactJS
Getting started with ReactJSKrishna Sunuwar
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript PromisesTomasz Bak
 
UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기UI 모듈화로 워라밸 지키기
UI 모듈화로 워라밸 지키기NAVER SHOPPING
 
React state managmenet with Redux
React state managmenet with ReduxReact state managmenet with Redux
React state managmenet with ReduxVedran Blaženka
 
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 appsMukul Jain
 

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 à Web improvements & service workers explained

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 changerSandro Paganotti
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)Domenic Denicola
 
PWA 與 Service Worker
PWA 與 Service WorkerPWA 與 Service Worker
PWA 與 Service WorkerAnna Su
 
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 promisesAnkit Agarwal
 
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 meansRobert Nyman
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !Gaurav Behere
 
Service Worker - Reliability bits
Service Worker - Reliability bitsService Worker - Reliability bits
Service Worker - Reliability bitsjungkees
 
Introduction to Service Workers | Matteo Manchi
Introduction to Service Workers | Matteo ManchiIntroduction to Service Workers | Matteo Manchi
Introduction to Service Workers | Matteo ManchiCodemotion
 
Promises, promises, and then observables
Promises, promises, and then observablesPromises, promises, and then observables
Promises, promises, and then observablesStefan Charsley
 
Offline First with Service Worker
Offline First with Service WorkerOffline First with Service Worker
Offline First with Service WorkerMuhammad Samu
 
Workboxで始める Service Worker
Workboxで始める Service WorkerWorkboxで始める Service Worker
Workboxで始める Service WorkerKazuyoshi Tsuchiya
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and httpAlexe Bogdan
 
Service workers
Service workersService workers
Service workersjungkees
 
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 PauloRobert Nyman
 
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-24Joachim Bengtsson
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS ServicesEyal Vardi
 
MeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenmentMeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenmentArtur Szott
 

Similaire à Web improvements & service workers explained (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

Have you tried listening?
Have you tried listening?Have you tried listening?
Have you tried listening?Robert Nyman
 
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 2017Robert Nyman
 
Introduction to Google Daydream
Introduction to Google DaydreamIntroduction to Google Daydream
Introduction to Google DaydreamRobert Nyman
 
Predictability for the Web
Predictability for the WebPredictability for the Web
Predictability for the WebRobert Nyman
 
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 2016Robert Nyman
 
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 2016Robert Nyman
 
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 IndonesiaRobert Nyman
 
Google tech & products
Google tech & productsGoogle tech & products
Google tech & productsRobert Nyman
 
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 ...Robert Nyman
 
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, JapanRobert Nyman
 
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...Robert Nyman
 
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...Robert Nyman
 
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 - IstanbulRobert Nyman
 
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 goRobert Nyman
 
Google, the future and possibilities
Google, the future and possibilitiesGoogle, the future and possibilities
Google, the future and possibilitiesRobert Nyman
 
Developer Relations in the Nordics
Developer Relations in the NordicsDeveloper Relations in the Nordics
Developer Relations in the NordicsRobert Nyman
 
What is Developer Relations?
What is Developer Relations?What is Developer Relations?
What is Developer Relations?Robert Nyman
 
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 meetupRobert Nyman
 
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, HelsinkiRobert Nyman
 
Google & gaming, IGDA - Helsinki
Google & gaming, IGDA - HelsinkiGoogle & gaming, IGDA - Helsinki
Google & gaming, IGDA - HelsinkiRobert 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

Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxAna-Maria Mihalceanu
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 

Dernier (20)

Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
A Glance At The Java Performance Toolbox
A Glance At The Java Performance ToolboxA Glance At The Java Performance Toolbox
A Glance At The Java Performance Toolbox
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 

Web improvements & service workers explained

  • 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.