Offline Strategies for HTML5 Web Applications - oscon13

Stephan Hochdörfer
Stephan HochdörferHead of Technology at bitExpert AG
Offline strategies for
HTML5 web applications
Stephan Hochdörfer, bitExpert AG
Offline strategies for HTML5 web applications
About me
 Stephan Hochdörfer
 Head of IT at bitExpert AG, Germany
 enjoying PHP since 1999
 S.Hochdoerfer@bitExpert.de
 @shochdoerfer
Offline strategies for HTML5 web applications
Storing data on the client? Seriously?
Offline strategies for HTML5 web applications
How did we solve these issues in the past?
Offline strategies for HTML5 web applications
Cookies are tasty, but not awesome!
Offline strategies for HTML5 web applications
IE DHTML behaviours, not sweet!
Offline strategies for HTML5 web applications
Flash Cookies are yummie!
Offline strategies for HTML5 web applications
Google Gears made it right. Sort of.
Can I haz alternative?
Offline strategies for HTML5 web applications
Offline strategies for HTML5 web applications
to the rescue!
Offline strategies for HTML5 web applications
[...] we take the next step,
announcing 2014 as the target for
Recommendation.
Jeff Jaffe, Chief Executive Officer, World Wide Web Consortium
Offline strategies for HTML5 web applications
Offline strategies for HTML5 web applications
What does „offline“ mean?
Offline strategies for HTML5 web applications
What does „offline“ mean?
Offline strategies for HTML5 web applications
Application Cache vs. Offline Storage
App Cache for caching static resources
Offline strategies for HTML5 web applications
HTML Page:
<!DOCTYPE html>
<html lang="en">
CACHE MANIFEST
js/app.js
css/app.css
favicon.ico
http://someotherdomain.com/image.png
<!DOCTYPE html>
<html lang="en" manifest="cache.manifest">
App Cache for caching static resources
Offline strategies for HTML5 web applications
HTML Page:
cache.manifest (served with Content-Type: text/cache-manifest):
App Cache for caching static resources
Offline strategies for HTML5 web applications
CACHE MANIFEST
# 2013-07-25
NETWORK:
data.php
CACHE:
/main/home
/main/app.js
/settings/home
/settings/app.js
http://myhost/logo.png
http://myhost/check.png
http://myhost/cross.png
App Cache for caching static resources
Offline strategies for HTML5 web applications
CACHE MANIFEST
# 2013-07-25
FALLBACK:
/ /offline.html
NETWORK:
*
App Cache – Some gotchas!
Offline strategies for HTML5 web applications
App Cache – Some gotchas!
Offline strategies for HTML5 web applications
1. Files are always(!) served from the
application cache.
App Cache – Some gotchas!
Offline strategies for HTML5 web applications
2. The application cache only updates
if the content of the manifest itself
has changed!
App Cache – Some gotchas!
Offline strategies for HTML5 web applications
3. If any of the files listed in the
CACHE section can't be retrieved, the
entire cache will be disregarded.
App Cache – Some gotchas!
Offline strategies for HTML5 web applications
4. If the manifest file itself can't be
retrieved, the cache will ignored!
App Cache – Some gotchas!
Offline strategies for HTML5 web applications
5. Non-cached resources will not load
on a cached page!
App Cache – Some gotchas!
Offline strategies for HTML5 web applications
6. The page needs to be reloaded,
otherwise the new resources do not
show up!
App Cache – Some gotchas!
Offline strategies for HTML5 web applications
7. To avoid the risk of caching
manifest files set expires headers!
App Cache – What to cache?
Offline strategies for HTML5 web applications
Yes:

Fonts

Splash image

App icon

Entry page

Fallback bootstrap
No:

CSS

HTML

Javascript
Storing dynamic data locally (in HTML5)
Offline strategies for HTML5 web applications
Offline strategies for HTML5 web applications
Example: Todolist application
Storing dynamic data locally (in HTML5)
Offline strategies for HTML5 web applications
Find the sources here:
github.com/bitExpert/html5-offline
Storing dynamic data locally (in HTML5)
Offline strategies for HTML5 web applications
Web Storage, Web SQL Database,
IndexedDB, File API
Web Storage
Offline strategies for HTML5 web applications
Web Storage
Offline strategies for HTML5 web applications
Very convenient form of offline
storage: simple key-value store
Web Storage: 2 different types
Offline strategies for HTML5 web applications
localStorage vs. sessionStorage
Web Storage: Add item
Offline strategies for HTML5 web applications
function add(item) {
try {
// for a new item set id
if((typeof item.id === "undefined")
|| (null == item.id) || ("" == item.id)) {
item.id = get_lastIndex() + 1;
}
// store object as string
localStorage.setItem(item.id,
JSON.stringify(item)
);
// update the index
set_lastIndex(item.id);
}
catch(ex) {
console.log(ex);
}
}
Web Storage: Modify item
Offline strategies for HTML5 web applications
function modify(item) {
try {
// store object as string
localStorage.setItem(item.id,
JSON.stringify(item)
);
}
catch(ex) {
console.log(ex);
}
}
Web Storage: Remove item
Offline strategies for HTML5 web applications
function remove (id) {
try {
localStorage.removeItem(id);
}
catch(ex) {
console.log(ex);
}
}
Web Storage: Read items
Offline strategies for HTML5 web applications
function read() {
try {
var lastIdx = get_lastIndex();
for(var i = 1; i <= lastIdx; i++) {
if(null !== localStorage.getItem(i)) {
// parse and render item
var item = JSON.parse(
localStorage.getItem(i)
);
}
}
}
catch(ex) {
console.log(ex);
}
}
Web Storage: Don`t like method calls?
Offline strategies for HTML5 web applications
Web Storage: Don`t like method calls?
Offline strategies for HTML5 web applications
var value = "my value";
// method call
localStorage.setItem("key", value);
// Array accessor
localStorage[key] = value;
// Property accessor
localStorage.key = value;
Web Storage: Pro
Offline strategies for HTML5 web applications
Most compatible format up to now.
Web Storage: Con
Offline strategies for HTML5 web applications
The data is not structured.
Web Storage: Con
Offline strategies for HTML5 web applications
No transaction support!
Web Storage: Con
Offline strategies for HTML5 web applications
Lack of automatically expiring storage.
Web Storage: Con
Offline strategies for HTML5 web applications
Inadequate information about
storage quota.
Web SQL Database
Offline strategies for HTML5 web applications
Web SQL Database
Offline strategies for HTML5 web applications
An offline SQL database based on
SQLite, an general-purpose SQL engine.
Web SQL Database: Callback methods
Offline strategies for HTML5 web applications
var onError = function(tx, ex) {
alert("Error: " + ex.message);
};
var onSuccess = function(tx, results) {
var len = results.rows.length;
for(var i = 0; i < len; i++) {
// render found todo item
render(results.rows.item(i));
}
};
Web SQL Database: Setup Database
Offline strategies for HTML5 web applications
// initalize the database connection
var db = openDatabase('todo', '1.0', 'Todo Database',
5 * 1024 * 1024 );
db.transaction(function (tx) {
tx.executeSql(
'CREATE TABLE IF NOT EXISTS todo '+
'(id INTEGER PRIMARY KEY ASC, todo TEXT)',
[],
onSuccess,
onError
);
});
Web SQL Database: Add item
Offline strategies for HTML5 web applications
function add(item) {
db.transaction(function(tx) {
tx.executeSql(
'INSERT INTO todo (todo) VALUES (?)',
[
item.todo
],
onSuccess,
onError
);
});
}
Web SQL Database: Modify item
Offline strategies for HTML5 web applications
function modify(item) {
db.transaction(function(tx) {
tx.executeSql(
'UPDATE todo SET todo = ? WHERE id = ?',
[
item.todo
item.id
],
onSuccess,
onError
);
});
}
Web SQL Database: Remove item
Offline strategies for HTML5 web applications
function remove(id) {
db.transaction(function (tx) {
tx.executeSql(
'DELETE FROM todo WHERE id = ?',
[
id
],
onSuccess,
onError
);
});
}
Web SQL Database: Read items
Offline strategies for HTML5 web applications
function read() {
db.transaction(function (tx) {
tx.executeSql(
'SELECT * FROM todo',
[],
onSuccess,
onError
);
});
}
Web SQL Database: Pro
Offline strategies for HTML5 web applications
It`s a SQL database within the browser!
Web SQL Database: Con
Offline strategies for HTML5 web applications
It`s a SQL database within the browser!
Web SQL Database: Con
Offline strategies for HTML5 web applications
SQLite is slooooow!
Web SQL Database: Con
Offline strategies for HTML5 web applications
The specification is no
longer part of HTML5!
IndexedDB
Offline strategies for HTML5 web applications
IndexedDB
Offline strategies for HTML5 web applications
A nice compromise between Web
Storage and Web SQL Database giving
you the best of both worlds.
IndexedDB: Preparation
Offline strategies for HTML5 web applications
// different browsers, different naming conventions
var indexedDB = window.indexedDB ||
window.webkitIndexedDB || window.mozIndexedDB ||
window.msIndexedDB;
var IDBTransaction = window.IDBTransaction ||
window.webkitIDBTransaction;
var IDBKeyRange = window.IDBKeyRange ||
window.webkitIDBKeyRange;
IndexedDB: Create object store
Offline strategies for HTML5 web applications
var db = null;
var request = indexedDB.open("todo");
request.onfailure = onError;
request.onsuccess = function(e) {
db = request.result;
var v = "1.0";
if(v != db.version) {
var verRequest = db.setVersion(v);
verRequest.onfailure = onError;
verRequest.onsuccess = function(e) {
var store = db.createObjectStore(
"todo",
{
keyPath: "id",
autoIncrement: true
}
);
e.target.transaction.oncomplete =
function() {};
};
}
};
IndexedDB: Add item
Offline strategies for HTML5 web applications
function add(item) {
try {
var trans = db.transaction(["todo"],
IDBTransaction.READ_WRITE);
var store = trans.objectStore("todo");
var request = store.put({
"todo": item.todo,
});
}
catch(ex) {
onError(ex);
}
}
IndexedDB: Modify item
Offline strategies for HTML5 web applications
function modify(item) {
try {
var trans = db.transaction(["todo"],
IDBTransaction.READ_WRITE);
var store = trans.objectStore("todo");
var request = store.put(item);
}
catch(ex) {
onError(ex);
}
}
IndexedDB: Remove item
Offline strategies for HTML5 web applications
function remove(id) {
try {
var trans = db.transaction(["todo"],
IDBTransaction.READ_WRITE);
var store = trans.objectStore("todo");
var request = store.delete(id);
}
catch(ex) {
onError(ex);
}
}
IndexedDB: Read items
Offline strategies for HTML5 web applications
function read () {
try {
var trans = db.transaction(["todo"],
IDBTransaction.READ);
var store = trans.objectStore("todo");
var keyRange = IDBKeyRange.lowerBound(0);
var cursorRequest = store.openCursor(keyRange);
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result == false) {
return;
}
// @TODO: render result.value
result.continue();
};
}
catch(ex) {
onError(ex);
}
}
File API
Offline strategies for HTML5 web applications
File API
Offline strategies for HTML5 web applications
FileReader API and FileWriter API
File API: Preparations
Offline strategies for HTML5 web applications
var onError = function(e) {
var msg = '';
switch(e.code) {
case FileError.QUOTA_EXCEEDED_ERR:
msg = 'QUOTA_EXCEEDED_ERR'; break;
case FileError.NOT_FOUND_ERR:
msg = 'NOT_FOUND_ERR'; break;
case FileError.SECURITY_ERR:
msg = 'SECURITY_ERR'; break;
case FileError.INVALID_MODIFICATION_ERR:
msg = 'INVALID_MODIFICATION_ERR'; break;
case FileError.INVALID_STATE_ERR:
msg = 'INVALID_STATE_ERR'; break;
default:
msg = 'Unknown Error'; break;
};
alert("Error: " + msg);
};
File API: Preparations
Offline strategies for HTML5 web applications
// File system has been prefixed as of Google Chrome 12
window.requestFileSystem = window.requestFileSystem ||
window.webkitRequestFileSystem;
window.BlobBuilder = window.BlobBuilder ||
window.WebKitBlobBuilder;
var size = 5 * 1024*1024; // 5MB
File API: Requesting quota
Offline strategies for HTML5 web applications
// request quota for persistent store
window.webkitStorageInfo.requestQuota(
PERSISTENT,
size,
function(grantedBytes) {
window.requestFileSystem(
PERSISTENT,
grantedBytes,
function(fs) {
// @TODO: access filesystem
}
}
}
}
Offline strategies for HTML5 web applications
File API: Add item
Offline strategies for HTML5 web applications
function add(item) {
window.webkitStorageInfo.requestQuota(
PERSISTENT,
size,
function(grantedBytes) {
window.requestFileSystem(
PERSISTENT,
grantedBytes,
function(fs){
writeToFile(fs, item);
},
onError
);
},
function(e) {
onError(e);
}
);
},
File API: Add item
Offline strategies for HTML5 web applications
function writeToFile(fs, item) {
fs.root.getFile(
'todo.txt',
{
create: true
},
function(fileEntry) {
fileEntry.createWriter(
function(fileWriter) {
var bb = new window.BlobBuilder();
bb.append(JSON.stringify(item)+
"n");
fileWriter.seek(fileWriter.length);
fileWriter.write(
bb.getBlob('text/plain'));
}, onError
);
}, onError
);
};
function writeToFile(fs, item) {
fs.root.getFile(
'todo.txt',
{
create: true
},
function(fileEntry) {
fileEntry.createWriter(
function(fileWriter) {
var bb = new window.BlobBuilder();
bb.append(JSON.stringify(item)+
"n");
fileWriter.seek(fileWriter.length);
fileWriter.write(
bb.getBlob('text/plain'));
}, onError
);
}, onError
);
};
File API: Add item
Offline strategies for HTML5 web applications
Deprecated!
function writeToFile(fs, item) {
fs.root.getFile(
'todo.txt',
{
create: true
},
function(fileEntry) {
fileEntry.createWriter(
function(fileWriter) {
var blob = new Blob([
JSON.stringify(item)+"n"
]);
fileWriter.seek(fileWriter.length);
fileWriter.write(blob);
}, onError
);
}, onError
);
};
File API: Add item
Offline strategies for HTML5 web applications
File API: Read items
Offline strategies for HTML5 web applications
function read() {
window.webkitStorageInfo.requestQuota(
PERSISTENT,
size,
function(grantedBytes) {
window.requestFileSystem(
PERSISTENT,
grantedBytes,
function(fs){
readFromFile(fs);
},
onError
);
},
function(e) {
onError(e);
}
);
}
File API: Read items
Offline strategies for HTML5 web applications
function readFromFile(fs) {
fs.root.getFile(
'todo.txt',
{
create: true
},
function(fileEntry) {
fileEntry.file(function(file){
var reader = new FileReader();
reader.onloadend = function(e) {
if (evt.target.readyState ==
FileReader.DONE) {
// process this.result
}
};
reader.readAsText(file);
});
}, onError
);
}
Browser support?
Offline strategies for HTML5 web applications
Browser support?
Offline strategies for HTML5 web applications
Source: http://caniuse.com
App Cache Web Storage WebSQL IndexedDB File API
IE 10.0 8.0 10.0 10.0 -
Firefox 11.0 11.0 11.0 11.0 19.0
Chrome 18.0 18.0 18.0 18.0 18.0
Safari 5.1 5.1 5.1 - -
Opera 12.1 12.1 12.1 - -
iOS Safari 3.2 3.2 3.2 - -
Android 2.1 2.1 2.1 - -
Storage limitations?
Offline strategies for HTML5 web applications
Storage limitations?
Offline strategies for HTML5 web applications
All storage technologies are limited
by quotas. Be aware of what you do!
Storage limitations?
Offline strategies for HTML5 web applications
App Cache Web Storage WebSQL IndexedDB File API
iOS 5.1 10 MB 5 MB 5 MB 5 MB
Android 4 unlimited 5 MB ? ?
Safari 5.2 unlimited 5 MB 5 MB 5 MB
Chrome 18 5 MB 5 MB unlimited unlimited unlimited
IE 10 50 MB 10 MB 500 MB 500 MB
Opera 11 50 MB 5 MB 5 MB 5 MB
Firefox 11 unlimited 10 MB 50 MB 50 MB
Thank you!
1 of 84

Recommended

Offline strategies for HTML5 web applications - frOSCon8 by
Offline strategies for HTML5 web applications - frOSCon8Offline strategies for HTML5 web applications - frOSCon8
Offline strategies for HTML5 web applications - frOSCon8Stephan Hochdörfer
9.5K views103 slides
Offline Strategies for HTML5 Web Applications - ipc13 by
Offline Strategies for HTML5 Web Applications - ipc13Offline Strategies for HTML5 Web Applications - ipc13
Offline Strategies for HTML5 Web Applications - ipc13Stephan Hochdörfer
2.1K views98 slides
Offline strategies for HTML5 web applications - ConFoo13 by
Offline strategies for HTML5 web applications - ConFoo13Offline strategies for HTML5 web applications - ConFoo13
Offline strategies for HTML5 web applications - ConFoo13Stephan Hochdörfer
38.1K views94 slides
Phing for power users - dpc_uncon13 by
Phing for power users - dpc_uncon13Phing for power users - dpc_uncon13
Phing for power users - dpc_uncon13Stephan Hochdörfer
2K views66 slides
Offline strategies for HTML5 web applications - IPC12 by
Offline strategies for HTML5 web applications - IPC12Offline strategies for HTML5 web applications - IPC12
Offline strategies for HTML5 web applications - IPC12Stephan Hochdörfer
836 views81 slides
Testing untestable Code - PFCongres 2010 by
Testing untestable Code - PFCongres 2010Testing untestable Code - PFCongres 2010
Testing untestable Code - PFCongres 2010Stephan Hochdörfer
989 views46 slides

More Related Content

What's hot

Turbogears Presentation by
Turbogears PresentationTurbogears Presentation
Turbogears Presentationdidip
1.3K views41 slides
Testing untestable code - DPC10 by
Testing untestable code - DPC10Testing untestable code - DPC10
Testing untestable code - DPC10Stephan Hochdörfer
1.3K views49 slides
Rego Deep Dive by
Rego Deep DiveRego Deep Dive
Rego Deep DiveTorin Sandall
8.4K views73 slides
Emerging threats jonkman_sans_cti_summit_2015 by
Emerging threats jonkman_sans_cti_summit_2015Emerging threats jonkman_sans_cti_summit_2015
Emerging threats jonkman_sans_cti_summit_2015Emerging Threats
2.6K views79 slides
Introduction to JavaScript for APEX Developers - Module 1: JavaScript Basics by
Introduction to JavaScript for APEX Developers - Module 1: JavaScript BasicsIntroduction to JavaScript for APEX Developers - Module 1: JavaScript Basics
Introduction to JavaScript for APEX Developers - Module 1: JavaScript BasicsDaniel McGhan
120 views63 slides
สปริงเฟรมเวิร์ค4.1 by
สปริงเฟรมเวิร์ค4.1สปริงเฟรมเวิร์ค4.1
สปริงเฟรมเวิร์ค4.1ทวิร พานิชสมบัติ
2.4K views47 slides

What's hot(20)

Turbogears Presentation by didip
Turbogears PresentationTurbogears Presentation
Turbogears Presentation
didip1.3K views
Emerging threats jonkman_sans_cti_summit_2015 by Emerging Threats
Emerging threats jonkman_sans_cti_summit_2015Emerging threats jonkman_sans_cti_summit_2015
Emerging threats jonkman_sans_cti_summit_2015
Emerging Threats2.6K views
Introduction to JavaScript for APEX Developers - Module 1: JavaScript Basics by Daniel McGhan
Introduction to JavaScript for APEX Developers - Module 1: JavaScript BasicsIntroduction to JavaScript for APEX Developers - Module 1: JavaScript Basics
Introduction to JavaScript for APEX Developers - Module 1: JavaScript Basics
Daniel McGhan120 views
OPA: The Cloud Native Policy Engine by Torin Sandall
OPA: The Cloud Native Policy EngineOPA: The Cloud Native Policy Engine
OPA: The Cloud Native Policy Engine
Torin Sandall5.3K views
KraQA #29 - Component level testing of react app, using enzyme by kraqa
KraQA #29 - Component level testing of react app, using enzymeKraQA #29 - Component level testing of react app, using enzyme
KraQA #29 - Component level testing of react app, using enzyme
kraqa544 views
Django Framework Overview forNon-Python Developers by Rosario Renga
Django Framework Overview forNon-Python DevelopersDjango Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python Developers
Rosario Renga3.1K views
jQuery Mobile & PhoneGap by Swiip
jQuery Mobile & PhoneGapjQuery Mobile & PhoneGap
jQuery Mobile & PhoneGap
Swiip3.4K views
Accelerated Adoption: HTML5 and CSS3 for ASP.NET Developers by Todd Anglin
Accelerated Adoption: HTML5 and CSS3 for ASP.NET DevelopersAccelerated Adoption: HTML5 and CSS3 for ASP.NET Developers
Accelerated Adoption: HTML5 and CSS3 for ASP.NET Developers
Todd Anglin5.3K views
Getting Started with HTML5 in Tech Com (STC 2012) by Peter Lubbers
Getting Started with HTML5 in Tech Com (STC 2012)Getting Started with HTML5 in Tech Com (STC 2012)
Getting Started with HTML5 in Tech Com (STC 2012)
Peter Lubbers45.4K views
HTML5, The Open Web, and what it means for you - Altran by Robert Nyman
HTML5, The Open Web, and what it means for you - AltranHTML5, The Open Web, and what it means for you - Altran
HTML5, The Open Web, and what it means for you - Altran
Robert Nyman6.4K views
HTML5 Semantics, Accessibility & Forms [Carsonified HTML5 Online Conference] by Aaron Gustafson
HTML5 Semantics, Accessibility & Forms [Carsonified HTML5 Online Conference]HTML5 Semantics, Accessibility & Forms [Carsonified HTML5 Online Conference]
HTML5 Semantics, Accessibility & Forms [Carsonified HTML5 Online Conference]
Aaron Gustafson13K views
Extracting Plugins And Gems From Rails Apps by Josh Nichols
Extracting Plugins And Gems From Rails AppsExtracting Plugins And Gems From Rails Apps
Extracting Plugins And Gems From Rails Apps
Josh Nichols1.3K views
Testing ASP.NET - Progressive.NET by Ben Hall
Testing ASP.NET - Progressive.NETTesting ASP.NET - Progressive.NET
Testing ASP.NET - Progressive.NET
Ben Hall5K views
HTML5 for PHP Developers - IPC by Mayflower GmbH
HTML5 for PHP Developers - IPCHTML5 for PHP Developers - IPC
HTML5 for PHP Developers - IPC
Mayflower GmbH52.9K views

Viewers also liked

Dependency Injection in PHP - dwx13 by
Dependency Injection in PHP - dwx13Dependency Injection in PHP - dwx13
Dependency Injection in PHP - dwx13Stephan Hochdörfer
2.3K views103 slides
Real World Dependency Injection - oscon13 by
Real World Dependency Injection - oscon13Real World Dependency Injection - oscon13
Real World Dependency Injection - oscon13Stephan Hochdörfer
3.6K views72 slides
OnConnectionLost: The life of an offline web application - JSUnconf 2015 by
OnConnectionLost: The life of an offline web application - JSUnconf 2015OnConnectionLost: The life of an offline web application - JSUnconf 2015
OnConnectionLost: The life of an offline web application - JSUnconf 2015Johannes Thönes
1.4K views85 slides
Incorporating Web Services in Mobile Applications - Web 2.0 San Fran 2009 by
Incorporating Web Services in Mobile Applications - Web 2.0 San Fran 2009Incorporating Web Services in Mobile Applications - Web 2.0 San Fran 2009
Incorporating Web Services in Mobile Applications - Web 2.0 San Fran 2009Aduci
6.5K views39 slides
HTML5: friend or foe (to Flash)? by
HTML5: friend or foe (to Flash)?HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?Remy Sharp
53.4K views162 slides
Updated: NW.js - Desktop Apps with Javascript by
Updated: NW.js - Desktop Apps with JavascriptUpdated: NW.js - Desktop Apps with Javascript
Updated: NW.js - Desktop Apps with JavascriptRalf Schwoebel
2.2K views15 slides

Viewers also liked(14)

OnConnectionLost: The life of an offline web application - JSUnconf 2015 by Johannes Thönes
OnConnectionLost: The life of an offline web application - JSUnconf 2015OnConnectionLost: The life of an offline web application - JSUnconf 2015
OnConnectionLost: The life of an offline web application - JSUnconf 2015
Johannes Thönes1.4K views
Incorporating Web Services in Mobile Applications - Web 2.0 San Fran 2009 by Aduci
Incorporating Web Services in Mobile Applications - Web 2.0 San Fran 2009Incorporating Web Services in Mobile Applications - Web 2.0 San Fran 2009
Incorporating Web Services in Mobile Applications - Web 2.0 San Fran 2009
Aduci6.5K views
HTML5: friend or foe (to Flash)? by Remy Sharp
HTML5: friend or foe (to Flash)?HTML5: friend or foe (to Flash)?
HTML5: friend or foe (to Flash)?
Remy Sharp53.4K views
Updated: NW.js - Desktop Apps with Javascript by Ralf Schwoebel
Updated: NW.js - Desktop Apps with JavascriptUpdated: NW.js - Desktop Apps with Javascript
Updated: NW.js - Desktop Apps with Javascript
Ralf Schwoebel2.2K views
Anatomy of mobile App development by Ralf Schwoebel
Anatomy of mobile App developmentAnatomy of mobile App development
Anatomy of mobile App development
Ralf Schwoebel1.8K views
From JavaEE to Android: Way in one click? by Sergii Zhuk
From JavaEE to Android: Way in one click?From JavaEE to Android: Way in one click?
From JavaEE to Android: Way in one click?
Sergii Zhuk1.7K views
HTML5 Offline Web Application by Allan Huang
HTML5 Offline Web ApplicationHTML5 Offline Web Application
HTML5 Offline Web Application
Allan Huang2.4K views
HTML5 AppCache: The Manifest by Ralf Schwoebel
HTML5 AppCache: The ManifestHTML5 AppCache: The Manifest
HTML5 AppCache: The Manifest
Ralf Schwoebel4.3K views
HTML5 Offline Web Applications (Silicon Valley User Group) by robinzimmermann
HTML5 Offline Web Applications (Silicon Valley User Group)HTML5 Offline Web Applications (Silicon Valley User Group)
HTML5 Offline Web Applications (Silicon Valley User Group)
robinzimmermann2.8K views
Online / Offline by Peter Rozek
Online / OfflineOnline / Offline
Online / Offline
Peter Rozek1.6K views
Anatomy of an HTML 5 mobile web app by Ivano Malavolta
Anatomy of an HTML 5 mobile web app Anatomy of an HTML 5 mobile web app
Anatomy of an HTML 5 mobile web app
Ivano Malavolta5.9K views
Html5 Offline Applications by Sunny Sharma
Html5 Offline Applications Html5 Offline Applications
Html5 Offline Applications
Sunny Sharma2.9K views

Similar to Offline Strategies for HTML5 Web Applications - oscon13

Taking your Web App for a walk by
Taking your Web App for a walkTaking your Web App for a walk
Taking your Web App for a walkJens-Christian Fischer
3.5K views93 slides
Attractive HTML5~開発者の視点から~ by
Attractive HTML5~開発者の視点から~Attractive HTML5~開発者の視点から~
Attractive HTML5~開発者の視点から~Sho Ito
1.3K views69 slides
The current status of html5 technology and standard by
The current status of html5 technology and standardThe current status of html5 technology and standard
The current status of html5 technology and standardWonsuk Lee
2.6K views76 slides
HTML5 Introduction by Dhepthi L by
HTML5 Introduction by Dhepthi LHTML5 Introduction by Dhepthi L
HTML5 Introduction by Dhepthi LSPRITLE SOFTWARE PRIVATE LIMIT ED
1.1K views18 slides
High Performance Web Pages - 20 new best practices by
High Performance Web Pages - 20 new best practicesHigh Performance Web Pages - 20 new best practices
High Performance Web Pages - 20 new best practicesStoyan Stefanov
50.1K views76 slides
Moving from Web 1.0 to Web 2.0 by
Moving from Web 1.0 to Web 2.0Moving from Web 1.0 to Web 2.0
Moving from Web 1.0 to Web 2.0Estelle Weyl
1.7K views42 slides

Similar to Offline Strategies for HTML5 Web Applications - oscon13(20)

Attractive HTML5~開発者の視点から~ by Sho Ito
Attractive HTML5~開発者の視点から~Attractive HTML5~開発者の視点から~
Attractive HTML5~開発者の視点から~
Sho Ito1.3K views
The current status of html5 technology and standard by Wonsuk Lee
The current status of html5 technology and standardThe current status of html5 technology and standard
The current status of html5 technology and standard
Wonsuk Lee2.6K views
High Performance Web Pages - 20 new best practices by Stoyan Stefanov
High Performance Web Pages - 20 new best practicesHigh Performance Web Pages - 20 new best practices
High Performance Web Pages - 20 new best practices
Stoyan Stefanov50.1K views
Moving from Web 1.0 to Web 2.0 by Estelle Weyl
Moving from Web 1.0 to Web 2.0Moving from Web 1.0 to Web 2.0
Moving from Web 1.0 to Web 2.0
Estelle Weyl1.7K views
"Progressive Web Apps" by Riza Fahmi (Hacktiv8) by Tech in Asia ID
"Progressive Web Apps" by Riza Fahmi	(Hacktiv8)"Progressive Web Apps" by Riza Fahmi	(Hacktiv8)
"Progressive Web Apps" by Riza Fahmi (Hacktiv8)
Tech in Asia ID313 views
Progressive Web Apps. What, why and how by Riza Fahmi
Progressive Web Apps. What, why and howProgressive Web Apps. What, why and how
Progressive Web Apps. What, why and how
Riza Fahmi2.5K views
Building Large Scale PHP Web Applications with Laravel 4 by Darwin Biler
Building Large Scale PHP Web Applications with Laravel 4Building Large Scale PHP Web Applications with Laravel 4
Building Large Scale PHP Web Applications with Laravel 4
Darwin Biler14.8K views
From Idea to App (or “How we roll at Small Town Heroes”) by Bramus Van Damme
From Idea to App (or “How we roll at Small Town Heroes”)From Idea to App (or “How we roll at Small Town Heroes”)
From Idea to App (or “How we roll at Small Town Heroes”)
Bramus Van Damme8.6K views
Developing web applications in 2010 by Ignacio Coloma
Developing web applications in 2010Developing web applications in 2010
Developing web applications in 2010
Ignacio Coloma595 views
Using jQuery Templates by Dan Wahlin
Using jQuery TemplatesUsing jQuery Templates
Using jQuery Templates
Dan Wahlin1.9K views
HTML5 Bootcamp: Essential HTML, CSS, & JavaScript by Todd Anglin
HTML5 Bootcamp: Essential HTML, CSS, & JavaScriptHTML5 Bootcamp: Essential HTML, CSS, & JavaScript
HTML5 Bootcamp: Essential HTML, CSS, & JavaScript
Todd Anglin15.7K views
SPTechCon 2014 How to develop and debug client side code in SharePoint by Mark Rackley
SPTechCon 2014 How to develop and debug client side code in SharePointSPTechCon 2014 How to develop and debug client side code in SharePoint
SPTechCon 2014 How to develop and debug client side code in SharePoint
Mark Rackley3.1K views
2014 SharePoint Saturday Melbourne Apps or not to Apps by Gilles Pommier
2014 SharePoint Saturday Melbourne Apps or not to Apps2014 SharePoint Saturday Melbourne Apps or not to Apps
2014 SharePoint Saturday Melbourne Apps or not to Apps
Gilles Pommier756 views

More from Stephan Hochdörfer

Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst... by
Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...
Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...Stephan Hochdörfer
2.7K views122 slides
Phing for power users - frOSCon8 by
Phing for power users - frOSCon8Phing for power users - frOSCon8
Phing for power users - frOSCon8Stephan Hochdörfer
1.7K views106 slides
Offline Strategien für HTML5 Web Applikationen - dwx13 by
Offline Strategien für HTML5 Web Applikationen - dwx13 Offline Strategien für HTML5 Web Applikationen - dwx13
Offline Strategien für HTML5 Web Applikationen - dwx13 Stephan Hochdörfer
2K views103 slides
Your Business. Your Language. Your Code - dpc13 by
Your Business. Your Language. Your Code - dpc13Your Business. Your Language. Your Code - dpc13
Your Business. Your Language. Your Code - dpc13Stephan Hochdörfer
1.2K views77 slides
Offline-Strategien für HTML5 Web Applikationen - wmka by
Offline-Strategien für HTML5 Web Applikationen - wmkaOffline-Strategien für HTML5 Web Applikationen - wmka
Offline-Strategien für HTML5 Web Applikationen - wmkaStephan Hochdörfer
1.9K views33 slides
Offline-Strategien für HTML5 Web Applikationen - bedcon13 by
Offline-Strategien für HTML5 Web Applikationen - bedcon13Offline-Strategien für HTML5 Web Applikationen - bedcon13
Offline-Strategien für HTML5 Web Applikationen - bedcon13Stephan Hochdörfer
1.8K views95 slides

More from Stephan Hochdörfer(20)

Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst... by Stephan Hochdörfer
Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...
Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...
Stephan Hochdörfer2.7K views
Offline Strategien für HTML5 Web Applikationen - dwx13 by Stephan Hochdörfer
Offline Strategien für HTML5 Web Applikationen - dwx13 Offline Strategien für HTML5 Web Applikationen - dwx13
Offline Strategien für HTML5 Web Applikationen - dwx13
Your Business. Your Language. Your Code - dpc13 by Stephan Hochdörfer
Your Business. Your Language. Your Code - dpc13Your Business. Your Language. Your Code - dpc13
Your Business. Your Language. Your Code - dpc13
Stephan Hochdörfer1.2K views
Offline-Strategien für HTML5 Web Applikationen - wmka by Stephan Hochdörfer
Offline-Strategien für HTML5 Web Applikationen - wmkaOffline-Strategien für HTML5 Web Applikationen - wmka
Offline-Strategien für HTML5 Web Applikationen - wmka
Stephan Hochdörfer1.9K views
Offline-Strategien für HTML5 Web Applikationen - bedcon13 by Stephan Hochdörfer
Offline-Strategien für HTML5 Web Applikationen - bedcon13Offline-Strategien für HTML5 Web Applikationen - bedcon13
Offline-Strategien für HTML5 Web Applikationen - bedcon13
Stephan Hochdörfer1.8K views
Offline-Strategien für HTML5Web Applikationen - WMMRN12 by Stephan Hochdörfer
Offline-Strategien für HTML5Web Applikationen - WMMRN12Offline-Strategien für HTML5Web Applikationen - WMMRN12
Offline-Strategien für HTML5Web Applikationen - WMMRN12
Stephan Hochdörfer1.1K views
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12 by Stephan Hochdörfer
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
Stephan Hochdörfer1.1K views
Wie Software-Generatoren die Welt verändern können - Herbstcampus12 by Stephan Hochdörfer
Wie Software-Generatoren die Welt verändern können - Herbstcampus12Wie Software-Generatoren die Welt verändern können - Herbstcampus12
Wie Software-Generatoren die Welt verändern können - Herbstcampus12
Stephan Hochdörfer1.3K views
Introducing a Software Generator Framework - JAZOON12 by Stephan Hochdörfer
Introducing a Software Generator Framework - JAZOON12Introducing a Software Generator Framework - JAZOON12
Introducing a Software Generator Framework - JAZOON12
Real World Dependency Injection SE - phpugrhh by Stephan Hochdörfer
Real World Dependency Injection SE - phpugrhhReal World Dependency Injection SE - phpugrhh
Real World Dependency Injection SE - phpugrhh
Stephan Hochdörfer1.2K views
Managing variability in software applications - scandev12 by Stephan Hochdörfer
Managing variability in software applications - scandev12Managing variability in software applications - scandev12
Managing variability in software applications - scandev12

Recently uploaded

iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas... by
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...Bernd Ruecker
26 views69 slides
Melek BEN MAHMOUD.pdf by
Melek BEN MAHMOUD.pdfMelek BEN MAHMOUD.pdf
Melek BEN MAHMOUD.pdfMelekBenMahmoud
14 views1 slide
1st parposal presentation.pptx by
1st parposal presentation.pptx1st parposal presentation.pptx
1st parposal presentation.pptxi238212
9 views3 slides
The Research Portal of Catalonia: Growing more (information) & more (services) by
The Research Portal of Catalonia: Growing more (information) & more (services)The Research Portal of Catalonia: Growing more (information) & more (services)
The Research Portal of Catalonia: Growing more (information) & more (services)CSUC - Consorci de Serveis Universitaris de Catalunya
73 views25 slides
Top 10 Strategic Technologies in 2024: AI and Automation by
Top 10 Strategic Technologies in 2024: AI and AutomationTop 10 Strategic Technologies in 2024: AI and Automation
Top 10 Strategic Technologies in 2024: AI and AutomationAutomationEdge Technologies
14 views14 slides
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive by
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveAutomating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveNetwork Automation Forum
21 views35 slides

Recently uploaded(20)

iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas... by Bernd Ruecker
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
Bernd Ruecker26 views
1st parposal presentation.pptx by i238212
1st parposal presentation.pptx1st parposal presentation.pptx
1st parposal presentation.pptx
i2382129 views
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive by Network Automation Forum
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLiveAutomating a World-Class Technology Conference; Behind the Scenes of CiscoLive
Automating a World-Class Technology Conference; Behind the Scenes of CiscoLive
6g - REPORT.pdf by Liveplex
6g - REPORT.pdf6g - REPORT.pdf
6g - REPORT.pdf
Liveplex9 views
Special_edition_innovator_2023.pdf by WillDavies22
Special_edition_innovator_2023.pdfSpecial_edition_innovator_2023.pdf
Special_edition_innovator_2023.pdf
WillDavies2216 views
STPI OctaNE CoE Brochure.pdf by madhurjyapb
STPI OctaNE CoE Brochure.pdfSTPI OctaNE CoE Brochure.pdf
STPI OctaNE CoE Brochure.pdf
madhurjyapb12 views
From chaos to control: Managing migrations and Microsoft 365 with ShareGate! by sammart93
From chaos to control: Managing migrations and Microsoft 365 with ShareGate!From chaos to control: Managing migrations and Microsoft 365 with ShareGate!
From chaos to control: Managing migrations and Microsoft 365 with ShareGate!
sammart939 views
Piloting & Scaling Successfully With Microsoft Viva by Richard Harbridge
Piloting & Scaling Successfully With Microsoft VivaPiloting & Scaling Successfully With Microsoft Viva
Piloting & Scaling Successfully With Microsoft Viva
Unit 1_Lecture 2_Physical Design of IoT.pdf by StephenTec
Unit 1_Lecture 2_Physical Design of IoT.pdfUnit 1_Lecture 2_Physical Design of IoT.pdf
Unit 1_Lecture 2_Physical Design of IoT.pdf
StephenTec11 views
The details of description: Techniques, tips, and tangents on alternative tex... by BookNet Canada
The details of description: Techniques, tips, and tangents on alternative tex...The details of description: Techniques, tips, and tangents on alternative tex...
The details of description: Techniques, tips, and tangents on alternative tex...
BookNet Canada121 views
HTTP headers that make your website go faster - devs.gent November 2023 by Thijs Feryn
HTTP headers that make your website go faster - devs.gent November 2023HTTP headers that make your website go faster - devs.gent November 2023
HTTP headers that make your website go faster - devs.gent November 2023
Thijs Feryn19 views
Spesifikasi Lengkap ASUS Vivobook Go 14 by Dot Semarang
Spesifikasi Lengkap ASUS Vivobook Go 14Spesifikasi Lengkap ASUS Vivobook Go 14
Spesifikasi Lengkap ASUS Vivobook Go 14
Dot Semarang35 views
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors by sugiuralab
TouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective SensorsTouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective Sensors
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors
sugiuralab15 views
Business Analyst Series 2023 - Week 3 Session 5 by DianaGray10
Business Analyst Series 2023 -  Week 3 Session 5Business Analyst Series 2023 -  Week 3 Session 5
Business Analyst Series 2023 - Week 3 Session 5
DianaGray10209 views

Offline Strategies for HTML5 Web Applications - oscon13

  • 1. Offline strategies for HTML5 web applications Stephan Hochdörfer, bitExpert AG
  • 2. Offline strategies for HTML5 web applications About me  Stephan Hochdörfer  Head of IT at bitExpert AG, Germany  enjoying PHP since 1999  S.Hochdoerfer@bitExpert.de  @shochdoerfer
  • 3. Offline strategies for HTML5 web applications Storing data on the client? Seriously?
  • 4. Offline strategies for HTML5 web applications How did we solve these issues in the past?
  • 5. Offline strategies for HTML5 web applications Cookies are tasty, but not awesome!
  • 6. Offline strategies for HTML5 web applications IE DHTML behaviours, not sweet!
  • 7. Offline strategies for HTML5 web applications Flash Cookies are yummie!
  • 8. Offline strategies for HTML5 web applications Google Gears made it right. Sort of.
  • 9. Can I haz alternative? Offline strategies for HTML5 web applications
  • 10. Offline strategies for HTML5 web applications to the rescue!
  • 11. Offline strategies for HTML5 web applications [...] we take the next step, announcing 2014 as the target for Recommendation. Jeff Jaffe, Chief Executive Officer, World Wide Web Consortium
  • 12. Offline strategies for HTML5 web applications
  • 13. Offline strategies for HTML5 web applications
  • 14. What does „offline“ mean? Offline strategies for HTML5 web applications
  • 15. What does „offline“ mean? Offline strategies for HTML5 web applications Application Cache vs. Offline Storage
  • 16. App Cache for caching static resources Offline strategies for HTML5 web applications HTML Page: <!DOCTYPE html> <html lang="en">
  • 17. CACHE MANIFEST js/app.js css/app.css favicon.ico http://someotherdomain.com/image.png <!DOCTYPE html> <html lang="en" manifest="cache.manifest"> App Cache for caching static resources Offline strategies for HTML5 web applications HTML Page: cache.manifest (served with Content-Type: text/cache-manifest):
  • 18. App Cache for caching static resources Offline strategies for HTML5 web applications CACHE MANIFEST # 2013-07-25 NETWORK: data.php CACHE: /main/home /main/app.js /settings/home /settings/app.js http://myhost/logo.png http://myhost/check.png http://myhost/cross.png
  • 19. App Cache for caching static resources Offline strategies for HTML5 web applications CACHE MANIFEST # 2013-07-25 FALLBACK: / /offline.html NETWORK: *
  • 20. App Cache – Some gotchas! Offline strategies for HTML5 web applications
  • 21. App Cache – Some gotchas! Offline strategies for HTML5 web applications 1. Files are always(!) served from the application cache.
  • 22. App Cache – Some gotchas! Offline strategies for HTML5 web applications 2. The application cache only updates if the content of the manifest itself has changed!
  • 23. App Cache – Some gotchas! Offline strategies for HTML5 web applications 3. If any of the files listed in the CACHE section can't be retrieved, the entire cache will be disregarded.
  • 24. App Cache – Some gotchas! Offline strategies for HTML5 web applications 4. If the manifest file itself can't be retrieved, the cache will ignored!
  • 25. App Cache – Some gotchas! Offline strategies for HTML5 web applications 5. Non-cached resources will not load on a cached page!
  • 26. App Cache – Some gotchas! Offline strategies for HTML5 web applications 6. The page needs to be reloaded, otherwise the new resources do not show up!
  • 27. App Cache – Some gotchas! Offline strategies for HTML5 web applications 7. To avoid the risk of caching manifest files set expires headers!
  • 28. App Cache – What to cache? Offline strategies for HTML5 web applications Yes:  Fonts  Splash image  App icon  Entry page  Fallback bootstrap No:  CSS  HTML  Javascript
  • 29. Storing dynamic data locally (in HTML5) Offline strategies for HTML5 web applications
  • 30. Offline strategies for HTML5 web applications Example: Todolist application
  • 31. Storing dynamic data locally (in HTML5) Offline strategies for HTML5 web applications Find the sources here: github.com/bitExpert/html5-offline
  • 32. Storing dynamic data locally (in HTML5) Offline strategies for HTML5 web applications Web Storage, Web SQL Database, IndexedDB, File API
  • 33. Web Storage Offline strategies for HTML5 web applications
  • 34. Web Storage Offline strategies for HTML5 web applications Very convenient form of offline storage: simple key-value store
  • 35. Web Storage: 2 different types Offline strategies for HTML5 web applications localStorage vs. sessionStorage
  • 36. Web Storage: Add item Offline strategies for HTML5 web applications function add(item) { try { // for a new item set id if((typeof item.id === "undefined") || (null == item.id) || ("" == item.id)) { item.id = get_lastIndex() + 1; } // store object as string localStorage.setItem(item.id, JSON.stringify(item) ); // update the index set_lastIndex(item.id); } catch(ex) { console.log(ex); } }
  • 37. Web Storage: Modify item Offline strategies for HTML5 web applications function modify(item) { try { // store object as string localStorage.setItem(item.id, JSON.stringify(item) ); } catch(ex) { console.log(ex); } }
  • 38. Web Storage: Remove item Offline strategies for HTML5 web applications function remove (id) { try { localStorage.removeItem(id); } catch(ex) { console.log(ex); } }
  • 39. Web Storage: Read items Offline strategies for HTML5 web applications function read() { try { var lastIdx = get_lastIndex(); for(var i = 1; i <= lastIdx; i++) { if(null !== localStorage.getItem(i)) { // parse and render item var item = JSON.parse( localStorage.getItem(i) ); } } } catch(ex) { console.log(ex); } }
  • 40. Web Storage: Don`t like method calls? Offline strategies for HTML5 web applications
  • 41. Web Storage: Don`t like method calls? Offline strategies for HTML5 web applications var value = "my value"; // method call localStorage.setItem("key", value); // Array accessor localStorage[key] = value; // Property accessor localStorage.key = value;
  • 42. Web Storage: Pro Offline strategies for HTML5 web applications Most compatible format up to now.
  • 43. Web Storage: Con Offline strategies for HTML5 web applications The data is not structured.
  • 44. Web Storage: Con Offline strategies for HTML5 web applications No transaction support!
  • 45. Web Storage: Con Offline strategies for HTML5 web applications Lack of automatically expiring storage.
  • 46. Web Storage: Con Offline strategies for HTML5 web applications Inadequate information about storage quota.
  • 47. Web SQL Database Offline strategies for HTML5 web applications
  • 48. Web SQL Database Offline strategies for HTML5 web applications An offline SQL database based on SQLite, an general-purpose SQL engine.
  • 49. Web SQL Database: Callback methods Offline strategies for HTML5 web applications var onError = function(tx, ex) { alert("Error: " + ex.message); }; var onSuccess = function(tx, results) { var len = results.rows.length; for(var i = 0; i < len; i++) { // render found todo item render(results.rows.item(i)); } };
  • 50. Web SQL Database: Setup Database Offline strategies for HTML5 web applications // initalize the database connection var db = openDatabase('todo', '1.0', 'Todo Database', 5 * 1024 * 1024 ); db.transaction(function (tx) { tx.executeSql( 'CREATE TABLE IF NOT EXISTS todo '+ '(id INTEGER PRIMARY KEY ASC, todo TEXT)', [], onSuccess, onError ); });
  • 51. Web SQL Database: Add item Offline strategies for HTML5 web applications function add(item) { db.transaction(function(tx) { tx.executeSql( 'INSERT INTO todo (todo) VALUES (?)', [ item.todo ], onSuccess, onError ); }); }
  • 52. Web SQL Database: Modify item Offline strategies for HTML5 web applications function modify(item) { db.transaction(function(tx) { tx.executeSql( 'UPDATE todo SET todo = ? WHERE id = ?', [ item.todo item.id ], onSuccess, onError ); }); }
  • 53. Web SQL Database: Remove item Offline strategies for HTML5 web applications function remove(id) { db.transaction(function (tx) { tx.executeSql( 'DELETE FROM todo WHERE id = ?', [ id ], onSuccess, onError ); }); }
  • 54. Web SQL Database: Read items Offline strategies for HTML5 web applications function read() { db.transaction(function (tx) { tx.executeSql( 'SELECT * FROM todo', [], onSuccess, onError ); }); }
  • 55. Web SQL Database: Pro Offline strategies for HTML5 web applications It`s a SQL database within the browser!
  • 56. Web SQL Database: Con Offline strategies for HTML5 web applications It`s a SQL database within the browser!
  • 57. Web SQL Database: Con Offline strategies for HTML5 web applications SQLite is slooooow!
  • 58. Web SQL Database: Con Offline strategies for HTML5 web applications The specification is no longer part of HTML5!
  • 59. IndexedDB Offline strategies for HTML5 web applications
  • 60. IndexedDB Offline strategies for HTML5 web applications A nice compromise between Web Storage and Web SQL Database giving you the best of both worlds.
  • 61. IndexedDB: Preparation Offline strategies for HTML5 web applications // different browsers, different naming conventions var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB; var IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction; var IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange;
  • 62. IndexedDB: Create object store Offline strategies for HTML5 web applications var db = null; var request = indexedDB.open("todo"); request.onfailure = onError; request.onsuccess = function(e) { db = request.result; var v = "1.0"; if(v != db.version) { var verRequest = db.setVersion(v); verRequest.onfailure = onError; verRequest.onsuccess = function(e) { var store = db.createObjectStore( "todo", { keyPath: "id", autoIncrement: true } ); e.target.transaction.oncomplete = function() {}; }; } };
  • 63. IndexedDB: Add item Offline strategies for HTML5 web applications function add(item) { try { var trans = db.transaction(["todo"], IDBTransaction.READ_WRITE); var store = trans.objectStore("todo"); var request = store.put({ "todo": item.todo, }); } catch(ex) { onError(ex); } }
  • 64. IndexedDB: Modify item Offline strategies for HTML5 web applications function modify(item) { try { var trans = db.transaction(["todo"], IDBTransaction.READ_WRITE); var store = trans.objectStore("todo"); var request = store.put(item); } catch(ex) { onError(ex); } }
  • 65. IndexedDB: Remove item Offline strategies for HTML5 web applications function remove(id) { try { var trans = db.transaction(["todo"], IDBTransaction.READ_WRITE); var store = trans.objectStore("todo"); var request = store.delete(id); } catch(ex) { onError(ex); } }
  • 66. IndexedDB: Read items Offline strategies for HTML5 web applications function read () { try { var trans = db.transaction(["todo"], IDBTransaction.READ); var store = trans.objectStore("todo"); var keyRange = IDBKeyRange.lowerBound(0); var cursorRequest = store.openCursor(keyRange); cursorRequest.onsuccess = function(e) { var result = e.target.result; if(!!result == false) { return; } // @TODO: render result.value result.continue(); }; } catch(ex) { onError(ex); } }
  • 67. File API Offline strategies for HTML5 web applications
  • 68. File API Offline strategies for HTML5 web applications FileReader API and FileWriter API
  • 69. File API: Preparations Offline strategies for HTML5 web applications var onError = function(e) { var msg = ''; switch(e.code) { case FileError.QUOTA_EXCEEDED_ERR: msg = 'QUOTA_EXCEEDED_ERR'; break; case FileError.NOT_FOUND_ERR: msg = 'NOT_FOUND_ERR'; break; case FileError.SECURITY_ERR: msg = 'SECURITY_ERR'; break; case FileError.INVALID_MODIFICATION_ERR: msg = 'INVALID_MODIFICATION_ERR'; break; case FileError.INVALID_STATE_ERR: msg = 'INVALID_STATE_ERR'; break; default: msg = 'Unknown Error'; break; }; alert("Error: " + msg); };
  • 70. File API: Preparations Offline strategies for HTML5 web applications // File system has been prefixed as of Google Chrome 12 window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder; var size = 5 * 1024*1024; // 5MB
  • 71. File API: Requesting quota Offline strategies for HTML5 web applications // request quota for persistent store window.webkitStorageInfo.requestQuota( PERSISTENT, size, function(grantedBytes) { window.requestFileSystem( PERSISTENT, grantedBytes, function(fs) { // @TODO: access filesystem } } } }
  • 72. Offline strategies for HTML5 web applications
  • 73. File API: Add item Offline strategies for HTML5 web applications function add(item) { window.webkitStorageInfo.requestQuota( PERSISTENT, size, function(grantedBytes) { window.requestFileSystem( PERSISTENT, grantedBytes, function(fs){ writeToFile(fs, item); }, onError ); }, function(e) { onError(e); } ); },
  • 74. File API: Add item Offline strategies for HTML5 web applications function writeToFile(fs, item) { fs.root.getFile( 'todo.txt', { create: true }, function(fileEntry) { fileEntry.createWriter( function(fileWriter) { var bb = new window.BlobBuilder(); bb.append(JSON.stringify(item)+ "n"); fileWriter.seek(fileWriter.length); fileWriter.write( bb.getBlob('text/plain')); }, onError ); }, onError ); };
  • 75. function writeToFile(fs, item) { fs.root.getFile( 'todo.txt', { create: true }, function(fileEntry) { fileEntry.createWriter( function(fileWriter) { var bb = new window.BlobBuilder(); bb.append(JSON.stringify(item)+ "n"); fileWriter.seek(fileWriter.length); fileWriter.write( bb.getBlob('text/plain')); }, onError ); }, onError ); }; File API: Add item Offline strategies for HTML5 web applications Deprecated!
  • 76. function writeToFile(fs, item) { fs.root.getFile( 'todo.txt', { create: true }, function(fileEntry) { fileEntry.createWriter( function(fileWriter) { var blob = new Blob([ JSON.stringify(item)+"n" ]); fileWriter.seek(fileWriter.length); fileWriter.write(blob); }, onError ); }, onError ); }; File API: Add item Offline strategies for HTML5 web applications
  • 77. File API: Read items Offline strategies for HTML5 web applications function read() { window.webkitStorageInfo.requestQuota( PERSISTENT, size, function(grantedBytes) { window.requestFileSystem( PERSISTENT, grantedBytes, function(fs){ readFromFile(fs); }, onError ); }, function(e) { onError(e); } ); }
  • 78. File API: Read items Offline strategies for HTML5 web applications function readFromFile(fs) { fs.root.getFile( 'todo.txt', { create: true }, function(fileEntry) { fileEntry.file(function(file){ var reader = new FileReader(); reader.onloadend = function(e) { if (evt.target.readyState == FileReader.DONE) { // process this.result } }; reader.readAsText(file); }); }, onError ); }
  • 79. Browser support? Offline strategies for HTML5 web applications
  • 80. Browser support? Offline strategies for HTML5 web applications Source: http://caniuse.com App Cache Web Storage WebSQL IndexedDB File API IE 10.0 8.0 10.0 10.0 - Firefox 11.0 11.0 11.0 11.0 19.0 Chrome 18.0 18.0 18.0 18.0 18.0 Safari 5.1 5.1 5.1 - - Opera 12.1 12.1 12.1 - - iOS Safari 3.2 3.2 3.2 - - Android 2.1 2.1 2.1 - -
  • 81. Storage limitations? Offline strategies for HTML5 web applications
  • 82. Storage limitations? Offline strategies for HTML5 web applications All storage technologies are limited by quotas. Be aware of what you do!
  • 83. Storage limitations? Offline strategies for HTML5 web applications App Cache Web Storage WebSQL IndexedDB File API iOS 5.1 10 MB 5 MB 5 MB 5 MB Android 4 unlimited 5 MB ? ? Safari 5.2 unlimited 5 MB 5 MB 5 MB Chrome 18 5 MB 5 MB unlimited unlimited unlimited IE 10 50 MB 10 MB 500 MB 500 MB Opera 11 50 MB 5 MB 5 MB 5 MB Firefox 11 unlimited 10 MB 50 MB 50 MB