• Save
Offline Strategies for HTML5 Web Applications - ipc13
Upcoming SlideShare
Loading in...5
×
 

Offline Strategies for HTML5 Web Applications - ipc13

on

  • 1,344 views

 

Statistics

Views

Total Views
1,344
Views on SlideShare
1,242
Embed Views
102

Actions

Likes
4
Downloads
0
Comments
0

3 Embeds 102

http://librosweb.es 79
http://lanyrd.com 22
http://translate.googleusercontent.com 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Offline Strategies for HTML5 Web Applications - ipc13 Offline Strategies for HTML5 Web Applications - ipc13 Presentation Transcript

    • 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 PHP since 1999 S.Hochdoerfer@bitExpert.de @shochdoerfer
    • 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.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 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">App Cache for caching static resourcesOffline strategies for HTML5 web applicationsHTML Page:cache.manifest (served with Content-Type: text/cache-manifest):
    • 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
    • CACHE MANIFEST# 2012­09­16FALLBACK:/ /offline.htmlNETWORK:*App Cache for caching static resourcesOffline strategies for HTML5 web applications
    • // 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
    • // 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
    • 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 cache.
    • App Cache – Some gotchas!Offline strategies for HTML5 web applications2. The application cache only updatesif the content of the manifest itselfhas changed!
    • 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.
    • App Cache – Some gotchas!Offline strategies for HTML5 web applications4. If the manifest file itself cant beretrieved, the cache will ignored!
    • 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 resources do notshow up!
    • App Cache – Some gotchas!Offline strategies for HTML5 web applications7. To avoid the risk of cachingmanifest files set expires headers!
    • App Cache – What to cache?Offline strategies for HTML5 web applicationsYes:FontsSplash imageApp iconEntry pageFallback bootstrapNo:CSSHTMLJavascript
    • 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­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
    • 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/bitExpert/html5-offline
    • Storing dynamic data locally (in HTML5)Offline strategies for HTML5 web applicationsWeb Storage, Web SQL Database,IndexedDB, File API
    • 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) || ("" == 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
    • 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
    • function remove (id) {try {localStorage.removeItem(id);}catch(ex) {console.log(ex);}}Web Storage: Remove itemOffline 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: Read itemsOffline strategies for HTML5 web applications
    • Web Storage: What about sessionStorage?Offline strategies for HTML5 web applications
    • Web Storage: What about sessionStorage?Offline strategies for HTML5 web applicationsReplace „localStorage „with „sessionStorage“
    • 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
    • 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;
    • 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 SQL engine.
    • 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
    • // 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
    • 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);});}
    • 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);});}
    • 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);});}
    • Web SQL Database: Read itemsOffline strategies for HTML5 web applicationsfunction read() {db.transaction(function (tx) {tx.executeSql(SELECT * FROM todo,[],onSuccess,onError);});}
    • 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 the best of both worlds.
    • 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.
    • // 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
    • 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
    • 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
    • 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
    • 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
    • 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);}}
    • 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;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
    • // 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
    • // 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
    • 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 itemOffline strategies for HTML5 web applications
    • 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);};
    • 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);  }  );}
    • 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
    • Am I online?Offline strategies for HTML5 web applications
    • 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
    • $.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
    • 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.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
    • Storage limitations?Offline strategies for HTML5 web applications
    • Storage limitations?Offline strategies for HTML5 web applicationsAll storage technologies are limitedby quotas. Be aware of what you do!
    • 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
    • Thank you!
    • http://joind.in/8797