Offline strategies forHTML5 web applicationsStephan Hochdörfer, bitExpert AG
Offline strategies for HTML5 web applicationsAbout me Stephan Hochdörfer Head of IT at bitExpert AG, Germany enjoying P...
Offline strategies for HTML5 web applicationsStoring data on the client?
Offline strategies for HTML5 web applicationsHow did we solve these issues in the past?
Offline strategies for HTML5 web applicationsCookies are tasty, but not awesome!
Offline strategies for HTML5 web applicationsIE DHTML behaviours, not sweet!
Offline strategies for HTML5 web applicationsFlash Cookies are yummie!
Offline strategies for HTML5 web applicationsGoogle Gears made it right. Sort of.
Can I haz alternative?Offline strategies for HTML5 web applications
Offline strategies for HTML5 web applicationsto the rescue!
Offline strategies for HTML5 web applications[...] we take the next step,announcing 2014 as the target forRecommendation.J...
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 applicationsApplication vs. Content
What does „offline“ mean?Offline strategies for HTML5 web applicationsApplication Cache vs. Offline Storage
App Cache for caching static resourcesOffline strategies for HTML5 web applications<!DOCTYPE html><html lang="en">HTML Page:
CACHE MANIFESTjs/app.jscss/app.cssfavicon.icohttp://someotherdomain.com/image.png<!DOCTYPE html><html lang="en" manifest="...
CACHE MANIFEST# 2012­09­16NETWORK:data.phpCACHE:/main/home/main/app.js/settings/home/settings/app.jshttp://myhost/logo.png...
CACHE MANIFEST# 2012­09­16FALLBACK:/ /offline.htmlNETWORK:*App Cache for caching static resourcesOffline strategies for HT...
// events fired by window.applicationCachewindow.applicationCache.onchecking = function(e) {log("Checking for updates");}w...
// Check if a new cache is available on page load.window.addEventListener(load, function(e) {  window.applicationCache.add...
App Cache – Some gotchas!Offline strategies for HTML5 web applications
App Cache – Some gotchas!Offline strategies for HTML5 web applications1. Files are always(!) served from theapplication ca...
App Cache – Some gotchas!Offline strategies for HTML5 web applications2. The application cache only updatesif the content ...
App Cache – Some gotchas!Offline strategies for HTML5 web applications3. If any of the files listed in theCACHE section ca...
App Cache – Some gotchas!Offline strategies for HTML5 web applications4. If the manifest file itself cant beretrieved, the...
App Cache – Some gotchas!Offline strategies for HTML5 web applications5. Non-cached resources will not loadon a cached page!
App Cache – Some gotchas!Offline strategies for HTML5 web applications6. The page needs to be reloaded,otherwise the new r...
App Cache – Some gotchas!Offline strategies for HTML5 web applications7. To avoid the risk of cachingmanifest files set ex...
App Cache – What to cache?Offline strategies for HTML5 web applicationsYes:FontsSplash imageApp iconEntry pageFallbac...
App Cache – What to cache?Offline strategies for HTML5 web applicationsUse the App Cacheonly for „static content“.
The Data URI schemeOffline strategies for HTML5 web applications
<!DOCTYPE HTML><html> <head>  <title>The Data URI scheme</title>  <style type="text/css">  ul.checklist li {    margin­lef...
Storing dynamic data locally (in HTML5)Offline strategies for HTML5 web applications
Offline strategies for HTML5 web applicationsExample: Todolist application
Storing dynamic data locally (in HTML5)Offline strategies for HTML5 web applicationsFind the sources here:github.com/bitEx...
Storing dynamic data locally (in HTML5)Offline strategies for HTML5 web applicationsWeb Storage, Web SQL Database,IndexedD...
Web StorageOffline strategies for HTML5 web applications
Web StorageOffline strategies for HTML5 web applicationsVery convenient form of offlinestorage: simple key-value store
Web Storage: 2 different typesOffline strategies for HTML5 web applicationslocalStorage vs. sessionStorage
function add(item) {try {// for a new item set idif((typeof item.id === "undefined")              || (null == item.id) || ...
function modify(item) {try {// store object as stringlocalStorage.setItem(item.id,              JSON.stringify(item)      ...
function remove (id) {try {localStorage.removeItem(id);}catch(ex) {console.log(ex);}}Web Storage: Remove itemOffline strat...
function read() {      try {      var lastIdx = get_lastIndex();      for(var i = 1; i <= lastIdx; i++) {      if(null !==...
Web Storage: What about sessionStorage?Offline strategies for HTML5 web applications
Web Storage: What about sessionStorage?Offline strategies for HTML5 web applicationsReplace „localStorage „with „sessionSt...
function add(item) {try {// for a new item set idif((typeof item.id === "undefined")              || (null == item.id) || ...
Web Storage: Don`t like method calls?Offline strategies for HTML5 web applicationsvar value = "my value";// method callloc...
Offline strategies for HTML5 web applicationsWhat`s stored in there?
Web Storage: ProOffline strategies for HTML5 web applicationsMost compatible format up to now.
Web Storage: ConOffline strategies for HTML5 web applicationsThe data is not structured.
Web Storage: ConOffline strategies for HTML5 web applicationsNo transaction support!
Web Storage: ConOffline strategies for HTML5 web applicationsLack of automatically expiring storage.
Web Storage: ConOffline strategies for HTML5 web applicationsInadequate information aboutstorage quota.
Web SQL DatabaseOffline strategies for HTML5 web applications
Web SQL DatabaseOffline strategies for HTML5 web applicationsAn offline SQL database based onSQLite, an general-purpose SQ...
var onError = function(tx, ex) {alert("Error: " + ex.message);};var onSuccess = function(tx, results) {var len = results.r...
// initalize the database connectionvar db = openDatabase(todo, 1.0, Todo Database,    5 * 1024 * 1024 );db.transaction(fu...
Web SQL Database: Add itemOffline strategies for HTML5 web applicationsfunction add(item) {db.transaction(function(tx) {tx...
Web SQL Database: Modify itemOffline strategies for HTML5 web applicationsfunction modify(item) {db.transaction(function(t...
Web SQL Database: Remove itemOffline strategies for HTML5 web applicationsfunction remove(id) {db.transaction(function (tx...
Web SQL Database: Read itemsOffline strategies for HTML5 web applicationsfunction read() {db.transaction(function (tx) {tx...
Web SQL Database: ProOffline strategies for HTML5 web applicationsIt`s a SQL database within the browser!
Web SQL Database: ConOffline strategies for HTML5 web applicationsIt`s a SQL database within the browser!
Web SQL Database: ConOffline strategies for HTML5 web applicationsSQLite is slooooow!
Web SQL Database: ConOffline strategies for HTML5 web applicationsThe specification is nolonger part of HTML5!
IndexedDBOffline strategies for HTML5 web applications
IndexedDBOffline strategies for HTML5 web applicationsA nice compromise between WebStorage and Web SQL Database givingyou ...
Web SQL Database vs. IndexedDBOffline strategies for HTML5 web applicationsCategory Web SQL IndexedDBLocation Tables conta...
// different browsers, different naming conventionsvar indexedDB = window.indexedDB ||    window.webkitIndexedDB || window...
var db = null;var request = indexedDB.open("todo");request.onfailure = onError;request.onsuccess = function(e) {db = reque...
function add(item) {try {var trans = db.transaction(["todo"],              IDBTransaction.READ_WRITE);var store   = trans....
function modify(item) {try {var trans = db.transaction(["todo"],              IDBTransaction.READ_WRITE);var store   = tra...
function remove(id) {try {var trans = db.transaction(["todo"],             IDBTransaction.READ_WRITE);var store   = trans....
IndexedDB: Read itemsOffline strategies for HTML5 web applicationsfunction read () {try {var trans = db.transaction(["todo...
File APIOffline strategies for HTML5 web applications
File APIOffline strategies for HTML5 web applicationsFileReader API and FileWriter API
var onError = function(e) {var msg = ;switch(e.code) {case FileError.QUOTA_EXCEEDED_ERR:msg = QUOTA_EXCEEDED_ERR; break;ca...
// File system has been prefixed as of Google Chrome 12window.requestFileSystem = window.requestFileSystem ||    window.we...
// request quota for persistent storewindow.webkitStorageInfo.requestQuota(PERSISTENT,size,function(grantedBytes) {window....
Offline strategies for HTML5 web applications
function add(item) {  window.webkitStorageInfo.requestQuota(  PERSISTENT,  size,  function(grantedBytes) {  window.request...
File API: Add itemOffline strategies for HTML5 web applicationsfunction writeToFile(fs, item) {fs.root.getFile(todo.txt,{c...
File API: Read itemsOffline strategies for HTML5 web applicationsfunction read() {  window.webkitStorageInfo.requestQuota(...
function readFromFile(fs) {fs.root.getFile(todo.txt,{create: true},function(fileEntry) {fileEntry.file(function(file){var ...
Am I online?Offline strategies for HTML5 web applications
document.body.addEventListener("online", function () {  // browser is online!}document.body.addEventListener("offline", fu...
$.ajax({  dataType: json,  url: http://myappurl.com/ping,  success: function(data){    // ping worked  },  error: function...
Your data in syncOffline strategies for HTML5 web applicationsPouchDB, the JavaScriptDatabase that syncs!
Frontend-Only Web AppsOffline strategies for HTML5 web applications„Hoodie is an architecture forfrontend-only web apps“
Browser support?Offline strategies for HTML5 web applications
Browser support?Offline strategies for HTML5 web applicationsApp Cache Web Storage WebSQL IndexedDB File API Data URIIE 10...
Storage limitations?Offline strategies for HTML5 web applications
Storage limitations?Offline strategies for HTML5 web applicationsAll storage technologies are limitedby quotas. Be aware o...
Storage limitations?Offline strategies for HTML5 web applicationsApp Cache Web Storage WebSQL IndexedDB File APIiOS 5.1 10...
Thank you!
http://joind.in/8797
Upcoming SlideShare
Loading in...5
×

Offline Strategies for HTML5 Web Applications - ipc13

1,249

Published on

Published in: Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,249
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
0
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

Transcript of "Offline Strategies for HTML5 Web Applications - ipc13"

  1. 1. Offline strategies forHTML5 web applicationsStephan Hochdörfer, bitExpert AG
  2. 2. Offline strategies for HTML5 web applicationsAbout me Stephan Hochdörfer Head of IT at bitExpert AG, Germany enjoying PHP since 1999 S.Hochdoerfer@bitExpert.de @shochdoerfer
  3. 3. Offline strategies for HTML5 web applicationsStoring data on the client?
  4. 4. Offline strategies for HTML5 web applicationsHow did we solve these issues in the past?
  5. 5. Offline strategies for HTML5 web applicationsCookies are tasty, but not awesome!
  6. 6. Offline strategies for HTML5 web applicationsIE DHTML behaviours, not sweet!
  7. 7. Offline strategies for HTML5 web applicationsFlash Cookies are yummie!
  8. 8. Offline strategies for HTML5 web applicationsGoogle Gears made it right. Sort of.
  9. 9. Can I haz alternative?Offline strategies for HTML5 web applications
  10. 10. Offline strategies for HTML5 web applicationsto the rescue!
  11. 11. Offline strategies for HTML5 web applications[...] we take the next step,announcing 2014 as the target forRecommendation.Jeff Jaffe, Chief Executive Officer, World Wide Web Consortium
  12. 12. Offline strategies for HTML5 web applications
  13. 13. Offline strategies for HTML5 web applications
  14. 14. What does „offline“ mean?Offline strategies for HTML5 web applications
  15. 15. What does „offline“ mean?Offline strategies for HTML5 web applicationsApplication vs. Content
  16. 16. What does „offline“ mean?Offline strategies for HTML5 web applicationsApplication Cache vs. Offline Storage
  17. 17. App Cache for caching static resourcesOffline strategies for HTML5 web applications<!DOCTYPE html><html lang="en">HTML Page:
  18. 18. CACHE MANIFESTjs/app.jscss/app.cssfavicon.icohttp://someotherdomain.com/image.png<!DOCTYPE html><html lang="en" manifest="cache.manifest">App Cache for caching static resourcesOffline strategies for HTML5 web applicationsHTML Page:cache.manifest (served with Content-Type: text/cache-manifest):
  19. 19. CACHE MANIFEST# 2012­09­16NETWORK:data.phpCACHE:/main/home/main/app.js/settings/home/settings/app.jshttp://myhost/logo.pnghttp://myhost/check.pnghttp://myhost/cross.pngApp Cache for caching static resourcesOffline strategies for HTML5 web applications
  20. 20. CACHE MANIFEST# 2012­09­16FALLBACK:/ /offline.htmlNETWORK:*App Cache for caching static resourcesOffline strategies for HTML5 web applications
  21. 21. // events fired by window.applicationCachewindow.applicationCache.onchecking = function(e) {log("Checking for updates");}window.applicationCache.onnoupdate = function(e) {log("No updates");}window.applicationCache.onupdateready = function(e) {log("Update ready");}window.applicationCache.onobsolete = function(e) {log("Obsolete");}window.applicationCache.ondownloading = function(e) {log("Downloading");}window.applicationCache.oncached = function(e) {log("Cached");}window.applicationCache.onerror = function(e) {log("Error");}// Log each filewindow.applicationCache.onprogress = function(e) {  log("Progress: downloaded file " + counter);  counter++;};App Cache ScriptingOffline strategies for HTML5 web applications
  22. 22. // Check if a new cache is available on page load.window.addEventListener(load, function(e) {  window.applicationCache.addEventListener(updateready,  function(e) {    if(window.applicationCache.status ==         window.applicationCache.UPDATEREADY) {      // Browser downloaded a new app cache.      // Swap it in and reload the page      window.applicationCache.swapCache();      if (confirm(New version is available. Load it?)) {        window.location.reload();      }    } else {      // Manifest didnt change...    }  }, false);}, false);App Cache ScriptingOffline strategies for HTML5 web applications
  23. 23. App Cache – Some gotchas!Offline strategies for HTML5 web applications
  24. 24. App Cache – Some gotchas!Offline strategies for HTML5 web applications1. Files are always(!) served from theapplication cache.
  25. 25. App Cache – Some gotchas!Offline strategies for HTML5 web applications2. The application cache only updatesif the content of the manifest itselfhas changed!
  26. 26. App Cache – Some gotchas!Offline strategies for HTML5 web applications3. If any of the files listed in theCACHE section cant be retrieved, theentire cache will be disregarded.
  27. 27. App Cache – Some gotchas!Offline strategies for HTML5 web applications4. If the manifest file itself cant beretrieved, the cache will ignored!
  28. 28. App Cache – Some gotchas!Offline strategies for HTML5 web applications5. Non-cached resources will not loadon a cached page!
  29. 29. App Cache – Some gotchas!Offline strategies for HTML5 web applications6. The page needs to be reloaded,otherwise the new resources do notshow up!
  30. 30. App Cache – Some gotchas!Offline strategies for HTML5 web applications7. To avoid the risk of cachingmanifest files set expires headers!
  31. 31. App Cache – What to cache?Offline strategies for HTML5 web applicationsYes:FontsSplash imageApp iconEntry pageFallback bootstrapNo:CSSHTMLJavascript
  32. 32. App Cache – What to cache?Offline strategies for HTML5 web applicationsUse the App Cacheonly for „static content“.
  33. 33. The Data URI schemeOffline strategies for HTML5 web applications
  34. 34. <!DOCTYPE HTML><html> <head>  <title>The Data URI scheme</title>  <style type="text/css">  ul.checklist li {    margin­left: 20px;    background: white url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==) no­repeat scroll left top;}  </style> </head> <body>  <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot"> </body></html>The Data URI schemeOffline strategies for HTML5 web applications
  35. 35. Storing dynamic data locally (in HTML5)Offline strategies for HTML5 web applications
  36. 36. Offline strategies for HTML5 web applicationsExample: Todolist application
  37. 37. Storing dynamic data locally (in HTML5)Offline strategies for HTML5 web applicationsFind the sources here:github.com/bitExpert/html5-offline
  38. 38. Storing dynamic data locally (in HTML5)Offline strategies for HTML5 web applicationsWeb Storage, Web SQL Database,IndexedDB, File API
  39. 39. Web StorageOffline strategies for HTML5 web applications
  40. 40. Web StorageOffline strategies for HTML5 web applicationsVery convenient form of offlinestorage: simple key-value store
  41. 41. Web Storage: 2 different typesOffline strategies for HTML5 web applicationslocalStorage vs. sessionStorage
  42. 42. function add(item) {try {// for a new item set idif((typeof item.id === "undefined")              || (null == item.id) || ("" == item.id)) {item.id = get_lastIndex() + 1;}// store object as stringlocalStorage.setItem(item.id,              JSON.stringify(item)         );// update the indexset_lastIndex(item.id);}catch(ex) {console.log(ex);}}Web Storage: Add itemOffline strategies for HTML5 web applications
  43. 43. function modify(item) {try {// store object as stringlocalStorage.setItem(item.id,              JSON.stringify(item)         );}catch(ex) {console.log(ex);}}Web Storage: Modify itemOffline strategies for HTML5 web applications
  44. 44. function remove (id) {try {localStorage.removeItem(id);}catch(ex) {console.log(ex);}}Web Storage: Remove itemOffline strategies for HTML5 web applications
  45. 45. 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: Read itemsOffline strategies for HTML5 web applications
  46. 46. Web Storage: What about sessionStorage?Offline strategies for HTML5 web applications
  47. 47. Web Storage: What about sessionStorage?Offline strategies for HTML5 web applicationsReplace „localStorage „with „sessionStorage“
  48. 48. function add(item) {try {// for a new item set idif((typeof item.id === "undefined")              || (null == item.id) || ("" == item.id)) {item.id = get_lastIndex() + 1;}// store object as stringsessionStorage.setItem(item.id,              JSON.stringify(item)         );// update the indexset_lastIndex(item.id);}catch(ex) {console.log(ex);}}Web Storage: Add item to sessionStorageOffline strategies for HTML5 web applications
  49. 49. Web Storage: Don`t like method calls?Offline strategies for HTML5 web applicationsvar value = "my value";// method calllocalStorage.setItem("key", value);// Array accessorlocalStorage[key] = value;// Property accessorlocalStorage.key = value;
  50. 50. Offline strategies for HTML5 web applicationsWhat`s stored in there?
  51. 51. Web Storage: ProOffline strategies for HTML5 web applicationsMost compatible format up to now.
  52. 52. Web Storage: ConOffline strategies for HTML5 web applicationsThe data is not structured.
  53. 53. Web Storage: ConOffline strategies for HTML5 web applicationsNo transaction support!
  54. 54. Web Storage: ConOffline strategies for HTML5 web applicationsLack of automatically expiring storage.
  55. 55. Web Storage: ConOffline strategies for HTML5 web applicationsInadequate information aboutstorage quota.
  56. 56. Web SQL DatabaseOffline strategies for HTML5 web applications
  57. 57. Web SQL DatabaseOffline strategies for HTML5 web applicationsAn offline SQL database based onSQLite, an general-purpose SQL engine.
  58. 58. 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 itemrender(results.rows.item(i));}};Web SQL Database: Callback methodsOffline strategies for HTML5 web applications
  59. 59. // initalize the database connectionvar 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: Setup DatabaseOffline strategies for HTML5 web applications
  60. 60. Web SQL Database: Add itemOffline strategies for HTML5 web applicationsfunction add(item) {db.transaction(function(tx) {tx.executeSql(INSERT INTO todo (todo) VALUES (?),[item.todo],onSuccess,onError);});}
  61. 61. Web SQL Database: Modify itemOffline strategies for HTML5 web applicationsfunction modify(item) {db.transaction(function(tx) {tx.executeSql(UPDATE todo SET todo = ? WHERE id = ?,[item.todoitem.id],onSuccess,onError);});}
  62. 62. Web SQL Database: Remove itemOffline strategies for HTML5 web applicationsfunction remove(id) {db.transaction(function (tx) {tx.executeSql(DELETE FROM todo WHERE id = ?,[id],onSuccess,onError);});}
  63. 63. Web SQL Database: Read itemsOffline strategies for HTML5 web applicationsfunction read() {db.transaction(function (tx) {tx.executeSql(SELECT * FROM todo,[],onSuccess,onError);});}
  64. 64. Web SQL Database: ProOffline strategies for HTML5 web applicationsIt`s a SQL database within the browser!
  65. 65. Web SQL Database: ConOffline strategies for HTML5 web applicationsIt`s a SQL database within the browser!
  66. 66. Web SQL Database: ConOffline strategies for HTML5 web applicationsSQLite is slooooow!
  67. 67. Web SQL Database: ConOffline strategies for HTML5 web applicationsThe specification is nolonger part of HTML5!
  68. 68. IndexedDBOffline strategies for HTML5 web applications
  69. 69. IndexedDBOffline strategies for HTML5 web applicationsA nice compromise between WebStorage and Web SQL Database givingyou the best of both worlds.
  70. 70. Web SQL Database vs. IndexedDBOffline strategies for HTML5 web applicationsCategory Web SQL IndexedDBLocation Tables contain columns androwsobjectStore contains Javascript objects andkeysQueryMechanismSQL Cursor APIs, Key Range APIs, andApplication CodeTransaction Lock can happen ondatabases, tables, or rowson READ_WRITEtransactionsLock can happen on databaseVERSION_CHANGE transaction, on anobjectStore READ_ONLY andREAD_WRITE transactions.TransactionCommitsTransaction creation isexplicit. Default is to rollbackunless we call commit.Transaction creation is explicit. Default is tocommit unless we call abort or there is anerror that is not caught.
  71. 71. // different browsers, different naming conventionsvar indexedDB = window.indexedDB ||    window.webkitIndexedDB || window.mozIndexedDB ||    window.msIndexedDB;var IDBTransaction = window.IDBTransaction ||   window.webkitIDBTransaction;var IDBKeyRange = window.IDBKeyRange ||    window.webkitIDBKeyRange;IndexedDB: PreparationOffline strategies for HTML5 web applications
  72. 72. 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: Create object storeOffline strategies for HTML5 web applications
  73. 73. 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: Add itemOffline strategies for HTML5 web applications
  74. 74. 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: Modify itemOffline strategies for HTML5 web applications
  75. 75. 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: Remove itemOffline strategies for HTML5 web applications
  76. 76. IndexedDB: Read itemsOffline strategies for HTML5 web applicationsfunction 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.valueresult.continue();};}catch(ex) {onError(ex);}}
  77. 77. File APIOffline strategies for HTML5 web applications
  78. 78. File APIOffline strategies for HTML5 web applicationsFileReader API and FileWriter API
  79. 79. 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: PreparationsOffline strategies for HTML5 web applications
  80. 80. // File system has been prefixed as of Google Chrome 12window.requestFileSystem = window.requestFileSystem ||    window.webkitRequestFileSystem;window.BlobBuilder = window.BlobBuilder ||     window.WebKitBlobBuilder;var size = 5 * 1024*1024; // 5MBFile API: PreparationsOffline strategies for HTML5 web applications
  81. 81. // request quota for persistent storewindow.webkitStorageInfo.requestQuota(PERSISTENT,size,function(grantedBytes) {window.requestFileSystem(PERSISTENT,grantedBytes,function(fs) {// @TODO: access filesystem}}}}File API: Requesting quotaOffline strategies for HTML5 web applications
  82. 82. Offline strategies for HTML5 web applications
  83. 83. 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 itemOffline strategies for HTML5 web applications
  84. 84. File API: Add itemOffline strategies for HTML5 web applicationsfunction 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);};
  85. 85. File API: Read itemsOffline strategies for HTML5 web applicationsfunction read() {  window.webkitStorageInfo.requestQuota(  PERSISTENT,  size,  function(grantedBytes) {  window.requestFileSystem(  PERSISTENT,  grantedBytes,  function(fs){  readFromFile(fs);  },  onError  );  },  function(e) {  onError(e);  }  );}
  86. 86. 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);}File API: Read itemsOffline strategies for HTML5 web applications
  87. 87. Am I online?Offline strategies for HTML5 web applications
  88. 88. document.body.addEventListener("online", function () {  // browser is online!}document.body.addEventListener("offline", function () {  // browser is not online!}Am I online?Offline strategies for HTML5 web applications
  89. 89. $.ajax({  dataType: json,  url: http://myappurl.com/ping,  success: function(data){    // ping worked  },  error: function() {    // ping failed ­> Server not reachable  }});Am I online? Another approach...Offline strategies for HTML5 web applications
  90. 90. Your data in syncOffline strategies for HTML5 web applicationsPouchDB, the JavaScriptDatabase that syncs!
  91. 91. Frontend-Only Web AppsOffline strategies for HTML5 web applications„Hoodie is an architecture forfrontend-only web apps“
  92. 92. Browser support?Offline strategies for HTML5 web applications
  93. 93. Browser support?Offline strategies for HTML5 web applicationsApp Cache Web Storage WebSQL IndexedDB File API Data URIIE 10.0 8.0 10.0 10.0 - 8.0*Firefox 11.0 11.0 11.0 11.0 19.0 16.0Chrome 18.0 18.0 18.0 18.0 18.0 18.0Safari 5.1 5.1 5.1 - - 5.1Opera 12.1 12.1 12.1 - - 12.1iOS Safari 3.2 3.2 3.2 - - 3.2Android 2.1 2.1 2.1 - - 2.1Source: http://caniuse.com
  94. 94. Storage limitations?Offline strategies for HTML5 web applications
  95. 95. Storage limitations?Offline strategies for HTML5 web applicationsAll storage technologies are limitedby quotas. Be aware of what you do!
  96. 96. Storage limitations?Offline strategies for HTML5 web applicationsApp Cache Web Storage WebSQL IndexedDB File APIiOS 5.1 10 MB 5 MB 5 MB 5 MBAndroid 4 unlimited 5 MB ? ?Safari 5.2 unlimited 5 MB 5 MB 5 MBChrome 18 5 MB 5 MB unlimited unlimited unlimitedIE 10 50 MB 10 MB 500 MB 500 MBOpera 11 50 MB 5 MB 5 MB 5 MBFirefox 11 unlimited 10 MB 50 MB 50 MB
  97. 97. Thank you!
  98. 98. http://joind.in/8797

×