SlideShare a Scribd company logo
Offline-first web apps 
Matt Andrews, Financial Times 
@andrewsmatt, mattandre.ws
Velocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web apps
• HTML5 
• Offline-first 
• Sideways-swipe-enabled 
• Add-to-home-screen-able 
• iOS 
• Web App
• HTML5 
• Offline-first 
• Sideways-swipe-enabled 
• Add-to-home-screen-able 
• iOS 
• Android 
• Web App
• HTML5 
• Offline-first 
• Sideways-swipe-enabled 
• Add-to-home-screen-able 
• iOS 
• Android 
• Windows 
• Web App
• HTML5 
• Offline-first 
• Sideways-swipe-enabled 
• Add-to-home-screen-able 
• iOS 
• Android 
• Windows 
• Firefox 
• Web App
• HTML5 
• Offline-first 
• Sideways-swipe-enabled 
• Add-to-home-screen-able 
• iOS 
• Android 
• Windows 
• Firefox 
• ALL THE THINGS 
• Web App
What’s so important 
about offline?
Velocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web apps
Velocity EU 2014 — Offline-first web apps
Internet Connections 
• Not just on or off 
• On can sometimes mean off 
• Slow can be worse than off
Velocity EU 2014 — Offline-first web apps
So why is FT app so slow?
AppCache 
CACHE MANIFEST 
/my-font.ttf 
/my-styles.css 
! 
! 
<DOCTYPE html> 
<html manifest="mywebapp.manifest">
AppCache 
CACHE MANIFEST 
/my-font.ttf 
/my-styles.css 
! 
NETWORK: 
* 
<DOCTYPE html> 
<html manifest="mywebapp.manifest">
AppCache Hacks 
• Varying the response of every page based on whether a cookie is set 
(hack needs to be added to our CDN as well as back end) 
• Returning an HTTP error on the manifest request when that cookie is 
not set; 
• Created an iframe to load a page that loads the manifest rather 
than referencing it directly. 
• Without the NETWORK: * hack in your AppCache manifest you will 
break all non-offline'd resources. 
• Putting all our API methods on a path starting with /api so that our 
FALLBACK doesn’t interfere with ajax requests. 
• Returning different Cache-Control headers on Internet Explorer 10+.
@andrewsmatt
Velocity EU 2014 — Offline-first web apps
Service Workers 
+ Fetch + Caches
Fetch API 
XMLHttpRequest revamped
var xhr = new XMLHttpRequest(); 
xhr.onreadystatechange = function() { 
if (xhr.readyState === 4) { 
if (xhr.status === 200) { 
alert(xhr.responseText); 
} else { 
alert('There was a problem.'); 
} 
} 
}; 
xhr.ontimeout = function() { 
alert('There was a problem.'); 
}; 
xhr.open('GET', 'http://a.b/c.html'); 
with XMLHttpRequest
fetch('http://a.b/c.html') 
.then(function(response) { 
return response.text(); // can be .json, .blob 
}) 
.then(function(text) { 
alert(text); 
}) 
.catch(function() { 
alert('There was a problem.'); 
}); 
with Fetch API
Using Fetch 
Native within Service Workers only 
Browser-only polyfill:- 
github.com/github/fetch 
‘Isomorphic’ Fetch Polyfill that works in 
Node and in the browser via 
Browserify:- 
bit.ly/iso-fetch
Cache API 
Caching that speaks JavaScript
caches.open(‘my-app’) 
.then(function(cache) { 
return cache 
.addAll([ 
‘/my-styles.css’, 
‘/my-font.ttf’ 
]); 
}); 
Pre-Cache URLs
caches.match(new Request(‘/my-styles.css’)) 
.then(function(response) { 
// got back /my-styles.css 
}); 
‘Fetch’ URLs from Cache
caches.open(‘my-app’) 
.then(function(cache) { 
return cache.put(‘/my-fake-endpoint’, 
new Response(‘Hello!’)); 
}); 
Put ‘fake’ responses into the Cache
Put ‘fake’ responses into the Cache 
WARNING: the difference between ‘add’ & ’put’ is 
different to the difference between IndexedDB’s 
‘add’ & ‘put’ 
add put 
IndexedDB INSERT INSERT OR UPDATE 
Service Worker 
Caches 
INSERT OR UPDATE INSERT OR UPDATE
caches.open(‘my-app’) 
.then(function(cache) { 
return cache.keys(); 
}) 
.then(function(keys) { 
return cache.addAll(keys); 
}); 
Update content in the Cache 
WARNING: This will ‘break’ any ‘fake requests’ that have 
been ‘put’ted 
WARNING: The Service Worker Cache is in addition to 
the regular HTTP Cache.
Service Workers
<DOCTYPE html> 
<html> 
<head><title>mattandre.ws</title></head> 
<body> 
<h1>My offline website</h1> 
<script> 
navigator.serviceWorker.register(‘./sw.js’) 
</script> 
</body> 
</html>
sw.js:- 
this.oninstall = function(event) { 
// prepare website to work offline, 
// e.g. cache resources 
}; 
this.onfetch = function(event) { 
// listen to, manipulate and/or respond 
// requests from your app 
};
Velocity EU 2014 — Offline-first web apps
sw.js:- 
this.oninstall = function(event) { 
var promise = caches.open(‘my-app’) 
.then(function(cache) { 
return cache 
.addAll([ 
‘/my-styles.css’, 
‘/my-font.ttf’ 
]); 
}); 
! 
event.waitUntil(promise); 
};
<DOCTYPE html> 
<html> 
<head><title>mattandre.ws</title></head> 
<body> 
<h1>My offline website</h1> 
<script> 
navigator.serviceWorker.register(‘./sw.js’) 
.then(function() { 
// installed 
}) 
.catch(function() { 
// didn’t install :( 
}); 
</script> 
</body> 
</html>
sw.js:- 
this.onfetch = function(event) { 
var promise; 
promise = caches.match(event.request) 
.catch(function() { 
return fetch(event.request); 
}); 
event.respondWith(promise); 
};
Service Worker 
Gotchas
chrome://flags#enable-experimental-web-platform-features
bit.ly/isserviceworkerready
No Caches 
The Service Worker Cache API does 
not work yet but a Polyfill exists that 
uses IndexedDB underneath:- 
bit.ly/caches-polyfill
Storage Limits 
• Every origin (protocol+domain+port) gets an 
allowance of offline storage, typically 50mb 
• Allowance shared between IndexedDB & 
Service Workers 
• Each origin only has access to data in its 
caches & databases.
Some JavaScript APIs are not 
available in Service Worker:- 
• LocalStorage 
• Synchronous ajax
https
You can use Service Workers to 
make offline-first websites… 
…or just to make normal 
websites faster.
Beyond Service 
Worker
Advanced Offline 
• Simple Caches not always enough 
• Use IndexedDB for more structured 
data, e.g. user preferences, bookmarks 
• Don’t use WebSQL it’s deprecated, use 
the polyfill. bit.ly/idbpolyfill
• Origins can have multiple IndexedDB 
databases 
• Each database can have multiple ‘object 
stores’ (like SQL tables) 
• An object store must have at least one 
index – IDB is NoSQL – can only be queried 
by pre-defined indexes 
• No free text search
function databaseOpen() {! 
! return new Promise(function(resolve, reject) {! 
! ! var version = 1;! 
! ! var request = indexedDB.open('todos', version);! 
! ! request.onupgradeneeded = function(e) {! 
! ! ! db = e.target.result;! 
! ! ! e.target.transaction.onerror = reject;! 
! ! ! db.createObjectStore('todo', {! 
! ! ! ! keyPath: '_id'! 
! ! ! });! 
! ! };! 
! ! request.onsuccess = function(e) {! 
! ! ! db = e.target.result;! 
! ! ! resolve();! 
! ! };! 
! ! request.onerror = reject;! 
! });! 
} raw javascript
Highly recommend 
Dexie.org, a Promise-based 
IndexedDB library
function databaseOpen() {! 
! var db = new Dexie('todos');! 
! db.version(1).stores({ todo: '_id' });! 
! return db.open();! 
} 
with Dexie.org
Summary 
• Service Worker is coming so get ready:- 
https, Promises, Caches Polyfill … 
• Use the Fetch API in your applications today 
bit.ly/iso-fetch / github.com/github/fetch 
• Want to use IDB? Use dexie.org. Want to support 
WebSQL? Use the polyfill bit.ly/idbpolyfill. 
• I’ve written tutorials on how to use all the HTML5 offline 
tech available for free here:- 
bit.ly/offline-workshop
Thanks! 
• Open Source:- 
github.com/ftlabs 
FastClick, Polyfill.io, DOM Delegate, Ellipsis, & more 
• Jobs:- 
labs.ft.com/jobs 
• Me:- 
@andrewsmatt / mattandre.ws

More Related Content

PDF
Webapps without the web
Remy Sharp
 
PDF
Future of Web Apps: Google Gears
dion
 
PDF
Rails 3: Dashing to the Finish
Yehuda Katz
 
PDF
The Peanut Butter Cup of Web-dev: Plack and single page web apps
John Anderson
 
PDF
iPhone Appleless Apps
Remy Sharp
 
PDF
Python for AngularJS
Jeff Schenck
 
PDF
Hidden Treasures in Project Wonder
WO Community
 
PDF
Caldera Learn - LoopConf WP API + Angular FTW Workshop
CalderaLearn
 
Webapps without the web
Remy Sharp
 
Future of Web Apps: Google Gears
dion
 
Rails 3: Dashing to the Finish
Yehuda Katz
 
The Peanut Butter Cup of Web-dev: Plack and single page web apps
John Anderson
 
iPhone Appleless Apps
Remy Sharp
 
Python for AngularJS
Jeff Schenck
 
Hidden Treasures in Project Wonder
WO Community
 
Caldera Learn - LoopConf WP API + Angular FTW Workshop
CalderaLearn
 

What's hot (20)

PDF
Containers & Dependency in Ember.js
Matthew Beale
 
PDF
Service worker - Offline Web
Bruno Oliveira
 
PDF
Choosing a Javascript Framework
All Things Open
 
PDF
Service worker API
Giorgio Natili
 
PDF
Ember and containers
Matthew Beale
 
PDF
Primefaces Nextgen Lju
Skills Matter
 
KEY
Making Django and NoSQL Play Nice
Alex Gaynor
 
PPTX
Good karma: UX Patterns and Unit Testing in Angular with Karma
ExoLeaders.com
 
PDF
Unobtrusive JavaScript
Vitaly Baum
 
PPTX
Maintainable JavaScript 2012
Nicholas Zakas
 
PDF
What happens in laravel 4 bootstraping
Jace Ju
 
PDF
Beyond DOM Manipulations: Building Stateful Modules with Events and Promises
Crashlytics
 
PPT
Jsp
Manav Prasad
 
PDF
Chef at WebMD
adamleff
 
PDF
Testing Ember Apps: Managing Dependency
Matthew Beale
 
PDF
Introduction to VueJS & The WordPress REST API
Caldera Labs
 
PDF
Integrating React.js Into a PHP Application
Andrew Rota
 
PDF
Excellent
Marco Otte-Witte
 
PPTX
WordCamp Ann Arbor 2015 Introduction to Backbone + WP REST API
Brian Hogg
 
Containers & Dependency in Ember.js
Matthew Beale
 
Service worker - Offline Web
Bruno Oliveira
 
Choosing a Javascript Framework
All Things Open
 
Service worker API
Giorgio Natili
 
Ember and containers
Matthew Beale
 
Primefaces Nextgen Lju
Skills Matter
 
Making Django and NoSQL Play Nice
Alex Gaynor
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
ExoLeaders.com
 
Unobtrusive JavaScript
Vitaly Baum
 
Maintainable JavaScript 2012
Nicholas Zakas
 
What happens in laravel 4 bootstraping
Jace Ju
 
Beyond DOM Manipulations: Building Stateful Modules with Events and Promises
Crashlytics
 
Chef at WebMD
adamleff
 
Testing Ember Apps: Managing Dependency
Matthew Beale
 
Introduction to VueJS & The WordPress REST API
Caldera Labs
 
Integrating React.js Into a PHP Application
Andrew Rota
 
Excellent
Marco Otte-Witte
 
WordCamp Ann Arbor 2015 Introduction to Backbone + WP REST API
Brian Hogg
 
Ad

Viewers also liked (20)

PPTX
Venues, banquet halls, party halls in e venuebooking
Usha Ramkumar
 
PPT
Mjd presentation1 (4)
t7260678
 
PPTX
Digital marketing-training-institute
softprostudent2
 
PDF
CHACOAL EVAPORATIVE COOLING TECHNOLOGY FOR STORAGE OF DWARF GER MARGLOBE TOMA...
International Journal of Technical Research & Application
 
PPTX
остесинт14
cdo_presentation
 
PPTX
MB Slides (15 March)
Rizwana Akhter
 
PPTX
Derechos de autor
lsanchezvalderrama
 
DOCX
Tiene algún sentido el bautismo hoy
Congregation of the Mission
 
PDF
Teorias administrativas
Maria Grant
 
PPTX
Hult Impact Challenge - IBM Watson Seismic
Sandeep Vete
 
PDF
Biologia (1)
carlos582
 
PDF
Trello et Basecamp: deux outils de gestion de projet pour les nuls
Samsa.fr
 
DOCX
стихи
Nadezhda Egovkina
 
PPTX
The Complete Guide to Planning Online Communications for Your Church
Concordia Technology Solutions
 
PDF
Rúbrica evaluar blog
Edgar Mata
 
PDF
Offline first, the painless way
Marcel Kalveram
 
PPTX
Trabajo informatoca RODRIGO
laurita1999
 
PPS
Sinfonia en blanco
Nat Di
 
PDF
ข้อสอบการงานอาชีพและเทคโนโลยี O-net ม.6
Thanawat Boontan
 
PDF
World Usability Day 2014 - David Lai — Stakeholders!
UXPALA
 
Venues, banquet halls, party halls in e venuebooking
Usha Ramkumar
 
Mjd presentation1 (4)
t7260678
 
Digital marketing-training-institute
softprostudent2
 
CHACOAL EVAPORATIVE COOLING TECHNOLOGY FOR STORAGE OF DWARF GER MARGLOBE TOMA...
International Journal of Technical Research & Application
 
остесинт14
cdo_presentation
 
MB Slides (15 March)
Rizwana Akhter
 
Derechos de autor
lsanchezvalderrama
 
Tiene algún sentido el bautismo hoy
Congregation of the Mission
 
Teorias administrativas
Maria Grant
 
Hult Impact Challenge - IBM Watson Seismic
Sandeep Vete
 
Biologia (1)
carlos582
 
Trello et Basecamp: deux outils de gestion de projet pour les nuls
Samsa.fr
 
стихи
Nadezhda Egovkina
 
The Complete Guide to Planning Online Communications for Your Church
Concordia Technology Solutions
 
Rúbrica evaluar blog
Edgar Mata
 
Offline first, the painless way
Marcel Kalveram
 
Trabajo informatoca RODRIGO
laurita1999
 
Sinfonia en blanco
Nat Di
 
ข้อสอบการงานอาชีพและเทคโนโลยี O-net ม.6
Thanawat Boontan
 
World Usability Day 2014 - David Lai — Stakeholders!
UXPALA
 
Ad

Similar to Velocity EU 2014 — Offline-first web apps (20)

PDF
Always on! ... or not?
Carsten Sandtner
 
PDF
Always on! Or not?
Carsten Sandtner
 
PPTX
Academy PRO: HTML5 Data storage
Binary Studio
 
PDF
JavaScript Service Worker Design Patterns for Better User Experience
reeder29
 
PPTX
Raising ux bar with offline first design
Kyrylo Reznykov
 
PDF
Stop the internet, i want to go offline
Boyan Mihaylov
 
PPTX
Progressive web applications
Tom Martin
 
PDF
FirefoxOS Meetup - Updates on Offline in HTML5 Web Apps
Natasha Rooney
 
PDF
Front-end. Global domination
Stfalcon Meetups
 
PDF
Frontend. Global domination.
Андрей Вандакуров
 
PDF
Updates on Offline: “My AppCache won’t come back” and “ServiceWorker Tricks ...
Natasha Rooney
 
PPT
Service Workers for Performance
Patrick Meenan
 
PPT
Intro to Service Worker API and its use cases
satejsahu
 
PDF
Service Worker Presentation
Kyle Dorman
 
PDF
Taking Web Apps Offline
Pedro Morais
 
PDF
The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)
David Pichsenmeister
 
PDF
Offline-First Mobile Web Apps with PouchDB, IBM Cloudant, and IBM Bluemix
IBM
 
PPTX
PWA basics for developers
Filip Rakowski
 
PDF
Offline progressive web apps with NodeJS and React
Ilia Idakiev
 
PDF
Offline Strategies for HTML5 Web Applications - oscon13
Stephan Hochdörfer
 
Always on! ... or not?
Carsten Sandtner
 
Always on! Or not?
Carsten Sandtner
 
Academy PRO: HTML5 Data storage
Binary Studio
 
JavaScript Service Worker Design Patterns for Better User Experience
reeder29
 
Raising ux bar with offline first design
Kyrylo Reznykov
 
Stop the internet, i want to go offline
Boyan Mihaylov
 
Progressive web applications
Tom Martin
 
FirefoxOS Meetup - Updates on Offline in HTML5 Web Apps
Natasha Rooney
 
Front-end. Global domination
Stfalcon Meetups
 
Frontend. Global domination.
Андрей Вандакуров
 
Updates on Offline: “My AppCache won’t come back” and “ServiceWorker Tricks ...
Natasha Rooney
 
Service Workers for Performance
Patrick Meenan
 
Intro to Service Worker API and its use cases
satejsahu
 
Service Worker Presentation
Kyle Dorman
 
Taking Web Apps Offline
Pedro Morais
 
The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)
David Pichsenmeister
 
Offline-First Mobile Web Apps with PouchDB, IBM Cloudant, and IBM Bluemix
IBM
 
PWA basics for developers
Filip Rakowski
 
Offline progressive web apps with NodeJS and React
Ilia Idakiev
 
Offline Strategies for HTML5 Web Applications - oscon13
Stephan Hochdörfer
 

Recently uploaded (20)

PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
PDF
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
The Future of Artificial Intelligence (AI)
Mukul
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Software Development Methodologies in 2025
KodekX
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
The Future of Mobile Is Context-Aware—Are You Ready?
iProgrammer Solutions Private Limited
 
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Doc9.....................................
SofiaCollazos
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
The Future of Artificial Intelligence (AI)
Mukul
 

Velocity EU 2014 — Offline-first web apps

  • 1. Offline-first web apps Matt Andrews, Financial Times @andrewsmatt, mattandre.ws
  • 4. • HTML5 • Offline-first • Sideways-swipe-enabled • Add-to-home-screen-able • iOS • Web App
  • 5. • HTML5 • Offline-first • Sideways-swipe-enabled • Add-to-home-screen-able • iOS • Android • Web App
  • 6. • HTML5 • Offline-first • Sideways-swipe-enabled • Add-to-home-screen-able • iOS • Android • Windows • Web App
  • 7. • HTML5 • Offline-first • Sideways-swipe-enabled • Add-to-home-screen-able • iOS • Android • Windows • Firefox • Web App
  • 8. • HTML5 • Offline-first • Sideways-swipe-enabled • Add-to-home-screen-able • iOS • Android • Windows • Firefox • ALL THE THINGS • Web App
  • 9. What’s so important about offline?
  • 13. Internet Connections • Not just on or off • On can sometimes mean off • Slow can be worse than off
  • 15. So why is FT app so slow?
  • 16. AppCache CACHE MANIFEST /my-font.ttf /my-styles.css ! ! <DOCTYPE html> <html manifest="mywebapp.manifest">
  • 17. AppCache CACHE MANIFEST /my-font.ttf /my-styles.css ! NETWORK: * <DOCTYPE html> <html manifest="mywebapp.manifest">
  • 18. AppCache Hacks • Varying the response of every page based on whether a cookie is set (hack needs to be added to our CDN as well as back end) • Returning an HTTP error on the manifest request when that cookie is not set; • Created an iframe to load a page that loads the manifest rather than referencing it directly. • Without the NETWORK: * hack in your AppCache manifest you will break all non-offline'd resources. • Putting all our API methods on a path starting with /api so that our FALLBACK doesn’t interfere with ajax requests. • Returning different Cache-Control headers on Internet Explorer 10+.
  • 21. Service Workers + Fetch + Caches
  • 23. var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 200) { alert(xhr.responseText); } else { alert('There was a problem.'); } } }; xhr.ontimeout = function() { alert('There was a problem.'); }; xhr.open('GET', 'http://a.b/c.html'); with XMLHttpRequest
  • 24. fetch('http://a.b/c.html') .then(function(response) { return response.text(); // can be .json, .blob }) .then(function(text) { alert(text); }) .catch(function() { alert('There was a problem.'); }); with Fetch API
  • 25. Using Fetch Native within Service Workers only Browser-only polyfill:- github.com/github/fetch ‘Isomorphic’ Fetch Polyfill that works in Node and in the browser via Browserify:- bit.ly/iso-fetch
  • 26. Cache API Caching that speaks JavaScript
  • 27. caches.open(‘my-app’) .then(function(cache) { return cache .addAll([ ‘/my-styles.css’, ‘/my-font.ttf’ ]); }); Pre-Cache URLs
  • 28. caches.match(new Request(‘/my-styles.css’)) .then(function(response) { // got back /my-styles.css }); ‘Fetch’ URLs from Cache
  • 29. caches.open(‘my-app’) .then(function(cache) { return cache.put(‘/my-fake-endpoint’, new Response(‘Hello!’)); }); Put ‘fake’ responses into the Cache
  • 30. Put ‘fake’ responses into the Cache WARNING: the difference between ‘add’ & ’put’ is different to the difference between IndexedDB’s ‘add’ & ‘put’ add put IndexedDB INSERT INSERT OR UPDATE Service Worker Caches INSERT OR UPDATE INSERT OR UPDATE
  • 31. caches.open(‘my-app’) .then(function(cache) { return cache.keys(); }) .then(function(keys) { return cache.addAll(keys); }); Update content in the Cache WARNING: This will ‘break’ any ‘fake requests’ that have been ‘put’ted WARNING: The Service Worker Cache is in addition to the regular HTTP Cache.
  • 33. <DOCTYPE html> <html> <head><title>mattandre.ws</title></head> <body> <h1>My offline website</h1> <script> navigator.serviceWorker.register(‘./sw.js’) </script> </body> </html>
  • 34. sw.js:- this.oninstall = function(event) { // prepare website to work offline, // e.g. cache resources }; this.onfetch = function(event) { // listen to, manipulate and/or respond // requests from your app };
  • 36. sw.js:- this.oninstall = function(event) { var promise = caches.open(‘my-app’) .then(function(cache) { return cache .addAll([ ‘/my-styles.css’, ‘/my-font.ttf’ ]); }); ! event.waitUntil(promise); };
  • 37. <DOCTYPE html> <html> <head><title>mattandre.ws</title></head> <body> <h1>My offline website</h1> <script> navigator.serviceWorker.register(‘./sw.js’) .then(function() { // installed }) .catch(function() { // didn’t install :( }); </script> </body> </html>
  • 38. sw.js:- this.onfetch = function(event) { var promise; promise = caches.match(event.request) .catch(function() { return fetch(event.request); }); event.respondWith(promise); };
  • 42. No Caches The Service Worker Cache API does not work yet but a Polyfill exists that uses IndexedDB underneath:- bit.ly/caches-polyfill
  • 43. Storage Limits • Every origin (protocol+domain+port) gets an allowance of offline storage, typically 50mb • Allowance shared between IndexedDB & Service Workers • Each origin only has access to data in its caches & databases.
  • 44. Some JavaScript APIs are not available in Service Worker:- • LocalStorage • Synchronous ajax
  • 45. https
  • 46. You can use Service Workers to make offline-first websites… …or just to make normal websites faster.
  • 48. Advanced Offline • Simple Caches not always enough • Use IndexedDB for more structured data, e.g. user preferences, bookmarks • Don’t use WebSQL it’s deprecated, use the polyfill. bit.ly/idbpolyfill
  • 49. • Origins can have multiple IndexedDB databases • Each database can have multiple ‘object stores’ (like SQL tables) • An object store must have at least one index – IDB is NoSQL – can only be queried by pre-defined indexes • No free text search
  • 50. function databaseOpen() {! ! return new Promise(function(resolve, reject) {! ! ! var version = 1;! ! ! var request = indexedDB.open('todos', version);! ! ! request.onupgradeneeded = function(e) {! ! ! ! db = e.target.result;! ! ! ! e.target.transaction.onerror = reject;! ! ! ! db.createObjectStore('todo', {! ! ! ! ! keyPath: '_id'! ! ! ! });! ! ! };! ! ! request.onsuccess = function(e) {! ! ! ! db = e.target.result;! ! ! ! resolve();! ! ! };! ! ! request.onerror = reject;! ! });! } raw javascript
  • 51. Highly recommend Dexie.org, a Promise-based IndexedDB library
  • 52. function databaseOpen() {! ! var db = new Dexie('todos');! ! db.version(1).stores({ todo: '_id' });! ! return db.open();! } with Dexie.org
  • 53. Summary • Service Worker is coming so get ready:- https, Promises, Caches Polyfill … • Use the Fetch API in your applications today bit.ly/iso-fetch / github.com/github/fetch • Want to use IDB? Use dexie.org. Want to support WebSQL? Use the polyfill bit.ly/idbpolyfill. • I’ve written tutorials on how to use all the HTML5 offline tech available for free here:- bit.ly/offline-workshop
  • 54. Thanks! • Open Source:- github.com/ftlabs FastClick, Polyfill.io, DOM Delegate, Ellipsis, & more • Jobs:- labs.ft.com/jobs • Me:- @andrewsmatt / mattandre.ws