Offline strategies for HTML5 web applications - ConFoo13

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 - ConFoo13
Offline strategies for HTML5 web applications - ConFoo13
Offline strategies for HTML5 web applications - ConFoo13
Offline strategies for HTML5 web applications - ConFoo13
Offline strategies for HTML5 web applications - ConFoo13
Offline strategies for HTML5 web applications - ConFoo13
Offline strategies for HTML5 web applications - ConFoo13
Offline strategies for HTML5 web applications - ConFoo13
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 - ConFoo13
Offline strategies for HTML5 web applications

 What does „offline“ mean?
Offline strategies for HTML5 web applications

 What does „offline“ mean?




             Application vs. Content
Offline strategies for HTML5 web applications

 What does „offline“ mean?




  Application Cache vs. Offline Storage
Offline strategies for HTML5 web applications

 App Cache for caching static resources
 HTML Page:
 <!DOCTYPE html>
 <html lang="en">
Offline strategies for HTML5 web applications

 App Cache for caching static resources
 HTML Page:
 <!DOCTYPE html>
 <html lang="en" manifest="cache.manifest">


 cache.manifest (served with Content-Type: text/cache-manifest):
 CACHE MANIFEST

 js/app.js
 css/app.css
 favicon.ico
 http://someotherdomain.com/image.png
Offline strategies for HTML5 web applications

 App Cache for caching static resources
 CACHE MANIFEST
 # 2012­09­16

 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
Offline strategies for HTML5 web applications

 App Cache for caching static resources
 CACHE MANIFEST
 # 2012­09­16

 FALLBACK:
 / /offline.html

 NETWORK:
 *
Offline strategies for HTML5 web applications

 App Cache Scripting
 // events fired by window.applicationCache
 window.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 file
 window.applicationCache.onprogress = function(e) {
   log("Progress: downloaded file " + counter);
   counter++;
 };
Offline strategies for HTML5 web applications

 App Cache Scripting
 // 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 didn't change...
     }
   }, false);

 }, false);
Offline strategies for HTML5 web applications

 App Cache – Some gotchas!
Offline strategies for HTML5 web applications

 App Cache – Some gotchas!




   1. Files are always(!) served from the
              application cache.
Offline strategies for HTML5 web applications

 App Cache – Some gotchas!




   2. The application cache only updates
    if the content of the manifest itself
               has changed!
Offline strategies for HTML5 web applications

 App Cache – Some gotchas!




     3. If any of the files listed in the
   CACHE section can't be retrieved, the
     entire cache will be disregarded.
Offline strategies for HTML5 web applications

 App Cache – Some gotchas!




     4. If the manifest file itself can't be
      retrieved, the cache will ignored!
Offline strategies for HTML5 web applications

 App Cache – Some gotchas!




   5. Non-cached resources will not load
            on a cached page!
Offline strategies for HTML5 web applications

 App Cache – Some gotchas!




     6. The page needs to be reloaded,
    otherwise the new resources do not
                 show up!
Offline strategies for HTML5 web applications

 App Cache – Some gotchas!




      7. To avoid the risk of caching
     manifest files set expires headers!
Offline strategies for HTML5 web applications

 App Cache – What to cache?

  Yes:                                 No:
  
    Fonts                              
                                         CSS
  
    Splash image                       
                                         HTML
  
    App icon                           
                                         Javascript
  
    Entry page
  
    Fallback bootstrap
Offline strategies for HTML5 web applications

 App Cache – What to cache?



               Use the App Cache
             only for „static content“.
Offline strategies for HTML5 web applications

 The Data URI scheme
Offline strategies for HTML5 web applications

 The Data URI scheme
 <!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,iVBORw0KGgoAAAANSUhEUgAAAAUAAA
 AFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAA
 O9TXL0Y4OHwAAAABJRU5ErkJggg==') no­repeat scroll left 
 top;
 }
   </style>
  </head>
  <body>
   <img 
 src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAA
 AFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAA
 O9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">
  </body>
 </html>
Offline strategies for HTML5 web applications

 Storing dynamic data locally (in HTML5)
Offline strategies for HTML5 web applications - ConFoo13
Offline strategies for HTML5 web applications

 Storing dynamic data locally (in HTML5)




           Find the sources here:
     github.com/bitExpert/html5-offline
Offline strategies for HTML5 web applications

 Storing dynamic data locally (in HTML5)




      Web Storage, Web SQL Database,
            IndexedDB, File API
Offline strategies for HTML5 web applications

 Web Storage
Offline strategies for HTML5 web applications

 Web Storage




        Very convenient form of offline
        storage: simple key-value store
Offline strategies for HTML5 web applications

 Web Storage: 2 different types




        localStorage vs. sessionStorage
Offline strategies for HTML5 web applications

 Web Storage: Add item
 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);
     }
 }
Offline strategies for HTML5 web applications

 Web Storage: Modify item
 function modify(item) {
     try {
          // store object as string
          localStorage.setItem(item.id, 
              JSON.stringify(item)
          );
     }
     catch(ex) {
          console.log(ex);
     }
 }
Offline strategies for HTML5 web applications

 Web Storage: Remove item
 function remove (id) {
     try {
          localStorage.removeItem(id);
     }
     catch(ex) {
          console.log(ex);
     }
 }
Offline strategies for HTML5 web applications

 Web Storage: Read items
 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);
       }
 }
Offline strategies for HTML5 web applications

 Web Storage: What about sessionStorage?
Offline strategies for HTML5 web applications

 Web Storage: What about sessionStorage?




               Replace „localStorage „
                with „sessionStorage“
Offline strategies for HTML5 web applications

 Web Storage: Add item to sessionStorage
 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
          sessionStorage.setItem(item.id, 
              JSON.stringify(item)
          );

         // update the index
         set_lastIndex(item.id);
     }
     catch(ex) {
         console.log(ex);
     }
 }
Offline strategies for HTML5 web applications

 Web Storage: Don`t like method calls?
 var value = "my value";

 // method call
 localStorage.setItem("key", value);

 // Array accessor
 localStorage[key] = value;

 // Property accessor
 localStorage.key = value;
Offline strategies for HTML5 web applications - ConFoo13
Offline strategies for HTML5 web applications

 Web Storage: Pro




     Most compatible format up to now.
Offline strategies for HTML5 web applications

 Web Storage: Con




            The data is not structured.
Offline strategies for HTML5 web applications

 Web Storage: Con




              No transaction support!
Offline strategies for HTML5 web applications

 Web Storage: Con




  Lack of automatically expiring storage.
Offline strategies for HTML5 web applications

 Web Storage: Con




        Inadequate information about
               storage quota.
Offline strategies for HTML5 web applications

 Web SQL Database
Offline strategies for HTML5 web applications

 Web SQL Database




   An offline SQL database based on
 SQLite, an general-purpose SQL engine.
Offline strategies for HTML5 web applications

 Web SQL Database: Callback methods
 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));
      }
 };
Offline strategies for HTML5 web applications

 Web SQL Database: Setup Database
 // 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
     );
 });
Offline strategies for HTML5 web applications

 Web SQL Database: Add item
 function add(item) {
     db.transaction(function(tx) {
          tx.executeSql(
              'INSERT INTO todo (todo) VALUES (?)',
              [
                   item.todo
              ],
              onSuccess,
              onError
          );
     });
 }
Offline strategies for HTML5 web applications

 Web SQL Database: Modify item
 function modify(item) {
     db.transaction(function(tx) {
          tx.executeSql(
              'UPDATE todo SET todo = ? WHERE id = ?',
              [
                   item.todo
                   item.id
              ],
              onSuccess,
              onError
          );
     });
 }
Offline strategies for HTML5 web applications

 Web SQL Database: Remove item
 function remove(id) {
     db.transaction(function (tx) {
          tx.executeSql(
              'DELETE FROM todo WHERE id = ?',
              [
                   id
              ],
              onSuccess,
              onError
          );
     });
 }
Offline strategies for HTML5 web applications

 Web SQL Database: Read items
 function read() {
     db.transaction(function (tx) {
          tx.executeSql(
              'SELECT * FROM todo',
              [],
              onSuccess,
              onError
          );
     });
 }
Offline strategies for HTML5 web applications

 Web SQL Database: Pro




It`s a SQL database within the browser!
Offline strategies for HTML5 web applications

 Web SQL Database: Con




It`s a SQL database within the browser!
Offline strategies for HTML5 web applications

 Web SQL Database: Con




                 SQLite is slooooow!
Offline strategies for HTML5 web applications

 Web SQL Database: Con




              The specification is no
              longer part of HTML5!
Offline strategies for HTML5 web applications

 IndexedDB
Offline strategies for HTML5 web applications

 IndexedDB



     A nice compromise between Web
  Storage and Web SQL Database giving
       you the best of both worlds.
Offline strategies for HTML5 web applications

 Web SQL Database vs. IndexedDB

 Category      Web SQL                            IndexedDB
 Location      Tables contain columns and         objectStore contains Javascript objects and
               rows                               keys
 Query         SQL                                Cursor APIs, Key Range APIs, and
 Mechanism                                        Application Code
 Transaction   Lock can happen on                 Lock can happen on database
               databases, tables, or rows         VERSION_CHANGE transaction, on an
               on READ_WRITE                      objectStore READ_ONLY and
               transactions                       READ_WRITE transactions.
 Transaction   Transaction creation is            Transaction creation is explicit. Default is to
 Commits       explicit. Default is to rollback   commit unless we call abort or there is an
               unless we call commit.             error that is not caught.
Offline strategies for HTML5 web applications

 IndexedDB: Preparation
 // 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;
Offline strategies for HTML5 web applications

 IndexedDB: Create object store
 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() {};
          };
     }
 };
Offline strategies for HTML5 web applications

 IndexedDB: Add item
 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);
     }
 }
Offline strategies for HTML5 web applications

 IndexedDB: Modify item
 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);
     }
 }
Offline strategies for HTML5 web applications

 IndexedDB: Remove item
 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);
     }
 }
Offline strategies for HTML5 web applications

 IndexedDB: Read items
 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);
     }
 }
Offline strategies for HTML5 web applications

 File API
Offline strategies for HTML5 web applications

 File API




      FileReader API and FileWriter API
Offline strategies for HTML5 web applications

 File API: Preparations
 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);
 };
Offline strategies for HTML5 web applications

 File API: Preparations
 // 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
Offline strategies for HTML5 web applications

 File API: Requesting quota
 // 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
Offline strategies for HTML5 web applications

 File API: Add item
 function add(item) {
        window.webkitStorageInfo.requestQuota(
             PERSISTENT,
             size,
             function(grantedBytes) {
                  window.requestFileSystem(
                       PERSISTENT,
                       grantedBytes,
                       function(fs){
                            writeToFile(fs, item);
                       },
                       onError
                  );
             },
             function(e) {
                  onError(e);
             }
        );
   },
Offline strategies for HTML5 web applications

 File API: Add item
 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
     );
 };
Offline strategies for HTML5 web applications

 File API: Read items
 function read() {
       window.webkitStorageInfo.requestQuota(
            PERSISTENT,
            size,
            function(grantedBytes) {
                 window.requestFileSystem(
                      PERSISTENT,
                      grantedBytes,
                      function(fs){
                           readFromFile(fs);
                      },
                      onError
                 );
            },
            function(e) {
                 onError(e);
            }
       );
 }
Offline strategies for HTML5 web applications

 File API: Read items
 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
     );
 }
Offline strategies for HTML5 web applications

 Am I online?
Offline strategies for HTML5 web applications

 Am I online?
 document.body.addEventListener("online", function () {
   // browser is online!
 }

 document.body.addEventListener("offline", function () {
   // browser is not online!
 }
Offline strategies for HTML5 web applications

 Am I online? Another approach...
 $.ajax({
   dataType: 'json',
   url: 'http://myappurl.com/ping',
   success: function(data){
     // ping worked
   },
   error: function() {
     // ping failed ­> Server not reachable
   }
 });
Offline strategies for HTML5 web applications

 Browser support?
              App Cache Web Storage WebSQL IndexedDB File API Data URI
 IE             10.0          8.0    10.0      10.0      -     8.0*
 Firefox        11.0          11.0   11.0      11.0     19.0   16.0
 Chrome         18.0          18.0   18.0      18.0     18.0   18.0
 Safari          5.1          5.1     5.1       -        -     5.1
 Opera          12.1          12.1   12.1       -        -     12.1
 iOS Safari      3.2          3.2     3.2       -        -     3.2
 Android         2.1          2.1     2.1       -        -     2.1



 Source: http://caniuse.com
Offline strategies for HTML5 web applications

 Storage limitations?
Offline strategies for HTML5 web applications

 Storage limitations?




    All storage technologies are limited
    by quotas. Be aware of what you do!
Offline strategies for HTML5 web applications

 Storage limitations?
               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!
http://joind.in/7913
1 of 94

Recommended

HTML5 Gaming Payment Platforms by
HTML5 Gaming Payment PlatformsHTML5 Gaming Payment Platforms
HTML5 Gaming Payment PlatformsJonathan LeBlanc
8.3K views33 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 - 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 - oscon13 by
Offline Strategies for HTML5 Web Applications - oscon13Offline Strategies for HTML5 Web Applications - oscon13
Offline Strategies for HTML5 Web Applications - oscon13Stephan Hochdörfer
2.8K views84 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 - pfCongres2012 by
Offline strategies for HTML5 web applications - pfCongres2012Offline strategies for HTML5 web applications - pfCongres2012
Offline strategies for HTML5 web applications - pfCongres2012Stephan Hochdörfer
811 views77 slides

More Related Content

What's hot

AtlasCamp 2015: Using add-ons to build add-ons by
AtlasCamp 2015: Using add-ons to build add-onsAtlasCamp 2015: Using add-ons to build add-ons
AtlasCamp 2015: Using add-ons to build add-onsAtlassian
1.6K views83 slides
AtlasCamp 2015: Connect everywhere - Cloud and Server by
AtlasCamp 2015: Connect everywhere - Cloud and ServerAtlasCamp 2015: Connect everywhere - Cloud and Server
AtlasCamp 2015: Connect everywhere - Cloud and ServerAtlassian
1.7K views43 slides
SharePoint Saturday Atlanta 2015 by
SharePoint Saturday Atlanta 2015SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015Pushkar Chivate
367 views41 slides
After max+phonegap by
After max+phonegapAfter max+phonegap
After max+phonegapyangdj
582 views54 slides
Rego Deep Dive by
Rego Deep DiveRego Deep Dive
Rego Deep DiveTorin Sandall
8.4K views73 slides
An Overview of Models in Django by
An Overview of Models in DjangoAn Overview of Models in Django
An Overview of Models in DjangoMichael Auritt
496 views54 slides

What's hot(20)

AtlasCamp 2015: Using add-ons to build add-ons by Atlassian
AtlasCamp 2015: Using add-ons to build add-onsAtlasCamp 2015: Using add-ons to build add-ons
AtlasCamp 2015: Using add-ons to build add-ons
Atlassian1.6K views
AtlasCamp 2015: Connect everywhere - Cloud and Server by Atlassian
AtlasCamp 2015: Connect everywhere - Cloud and ServerAtlasCamp 2015: Connect everywhere - Cloud and Server
AtlasCamp 2015: Connect everywhere - Cloud and Server
Atlassian1.7K views
SharePoint Saturday Atlanta 2015 by Pushkar Chivate
SharePoint Saturday Atlanta 2015SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015
Pushkar Chivate367 views
After max+phonegap by yangdj
After max+phonegapAfter max+phonegap
After max+phonegap
yangdj582 views
An Overview of Models in Django by Michael Auritt
An Overview of Models in DjangoAn Overview of Models in Django
An Overview of Models in Django
Michael Auritt496 views
Oleh Zasadnyy "Progressive Web Apps: line between web and native apps become ... by IT Event
Oleh Zasadnyy "Progressive Web Apps: line between web and native apps become ...Oleh Zasadnyy "Progressive Web Apps: line between web and native apps become ...
Oleh Zasadnyy "Progressive Web Apps: line between web and native apps become ...
IT Event205 views
Building AOL's High Performance, Enterprise Wide Mail Application With Silver... by goodfriday
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
goodfriday948 views
Web Components: The future of Web Application Development by Jermaine Oppong
Web Components: The future of Web Application DevelopmentWeb Components: The future of Web Application Development
Web Components: The future of Web Application Development
Jermaine Oppong743 views
Module 3: Working with the DOM and jQuery by Daniel McGhan
Module 3: Working with the DOM and jQueryModule 3: Working with the DOM and jQuery
Module 3: Working with the DOM and jQuery
Daniel McGhan684 views
Vaadin 8 and 10 by Peter Lehto
Vaadin 8 and 10Vaadin 8 and 10
Vaadin 8 and 10
Peter Lehto1.6K views
Open Social In The Enterprise by Tim Moore
Open Social In The EnterpriseOpen Social In The Enterprise
Open Social In The Enterprise
Tim Moore718 views
CiklumJavaSat_15112011:Alex Kruk VMForce by Ciklum Ukraine
CiklumJavaSat_15112011:Alex Kruk VMForceCiklumJavaSat_15112011:Alex Kruk VMForce
CiklumJavaSat_15112011:Alex Kruk VMForce
Ciklum Ukraine615 views
Crossing platforms with JavaScript & React by Robert DeLuca
Crossing platforms with JavaScript & React Crossing platforms with JavaScript & React
Crossing platforms with JavaScript & React
Robert DeLuca182 views
Introduction to Palm's Mojo SDK by Brendan Lim
Introduction to Palm's Mojo SDKIntroduction to Palm's Mojo SDK
Introduction to Palm's Mojo SDK
Brendan Lim1.6K views

Viewers also liked

Online vs offline: the importance of an integrated experience by
Online vs offline: the importance of an integrated experienceOnline vs offline: the importance of an integrated experience
Online vs offline: the importance of an integrated experienceGalland.be bvba
4K views74 slides
Test presentation by
Test presentationTest presentation
Test presentationdoucetteb
342 views1 slide
Mobile assisted language learning by
Mobile assisted language learningMobile assisted language learning
Mobile assisted language learningAbdel-Fattah Adel
2.9K views5 slides
Mobile assisted language learning (mall) by
Mobile assisted language learning (mall)Mobile assisted language learning (mall)
Mobile assisted language learning (mall)MahmoudAlSaidi
17.7K views41 slides
presentation on static website design by
presentation on static website designpresentation on static website design
presentation on static website designjyotiyadav1926
7K views20 slides

Viewers also liked(13)

Online vs offline: the importance of an integrated experience by Galland.be bvba
Online vs offline: the importance of an integrated experienceOnline vs offline: the importance of an integrated experience
Online vs offline: the importance of an integrated experience
Galland.be bvba4K views
Test presentation by doucetteb
Test presentationTest presentation
Test presentation
doucetteb342 views
Mobile assisted language learning (mall) by MahmoudAlSaidi
Mobile assisted language learning (mall)Mobile assisted language learning (mall)
Mobile assisted language learning (mall)
MahmoudAlSaidi17.7K views
presentation on static website design by jyotiyadav1926
presentation on static website designpresentation on static website design
presentation on static website design
jyotiyadav19267K views
Internet marketing strategy and practice by AdCMO
Internet marketing strategy and practiceInternet marketing strategy and practice
Internet marketing strategy and practice
AdCMO20K views
Blended Learning in Your Classroom by Evan Abbey
Blended Learning in Your ClassroomBlended Learning in Your Classroom
Blended Learning in Your Classroom
Evan Abbey19K views
Establishing a Successful International Web Presence #InternationalSEO #SMX W... by Aleyda Solís
Establishing a Successful International Web Presence #InternationalSEO #SMX W...Establishing a Successful International Web Presence #InternationalSEO #SMX W...
Establishing a Successful International Web Presence #InternationalSEO #SMX W...
Aleyda Solís3.4K views

Similar to Offline strategies for HTML5 web applications - ConFoo13

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
Attractive HTML5~開発者の視点から~ by
Attractive HTML5~開発者の視点から~Attractive HTML5~開発者の視点から~
Attractive HTML5~開発者の視点から~Sho Ito
1.3K views69 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
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
Html5 by
Html5Html5
Html5Zahin Omar Alwa
764 views25 slides
2310 b 15 by
2310 b 152310 b 15
2310 b 15Krazy Koder
402 views33 slides

Similar to Offline strategies for HTML5 web applications - ConFoo13(20)

Offline strategies for HTML5 web applications - IPC12 by Stephan Hochdörfer
Offline strategies for HTML5 web applications - IPC12Offline strategies for HTML5 web applications - IPC12
Offline strategies for HTML5 web applications - IPC12
Attractive HTML5~開発者の視点から~ by Sho Ito
Attractive HTML5~開発者の視点から~Attractive HTML5~開発者の視点から~
Attractive HTML5~開発者の視点から~
Sho Ito1.3K 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
The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS) by David Pichsenmeister
The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)
The Hitchhikers Guide To Html5 Offline Strategies (+firefoxOS)
David Pichsenmeister13.6K 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
Creating Data Driven HTML5 Applications by Gil Fink
Creating Data Driven HTML5 ApplicationsCreating Data Driven HTML5 Applications
Creating Data Driven HTML5 Applications
Gil Fink1.5K views
Saving Time And Effort With QuickBase Api - Sergio Haro by QuickBase, Inc.
Saving Time And Effort With QuickBase Api - Sergio HaroSaving Time And Effort With QuickBase Api - Sergio Haro
Saving Time And Effort With QuickBase Api - Sergio Haro
QuickBase, Inc.7.8K views
HTML5 on Mobile by Adam Lu
HTML5 on MobileHTML5 on Mobile
HTML5 on Mobile
Adam Lu8.4K views
Html5 and beyond the next generation of mobile web applications - Touch Tou... by RIA RUI Society
Html5 and beyond   the next generation of mobile web applications - Touch Tou...Html5 and beyond   the next generation of mobile web applications - Touch Tou...
Html5 and beyond the next generation of mobile web applications - Touch Tou...
RIA RUI Society1.1K 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
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
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
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

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

Recently uploaded

Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue by
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlueElevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlueShapeBlue
179 views7 slides
DRBD Deep Dive - Philipp Reisner - LINBIT by
DRBD Deep Dive - Philipp Reisner - LINBITDRBD Deep Dive - Philipp Reisner - LINBIT
DRBD Deep Dive - Philipp Reisner - LINBITShapeBlue
140 views21 slides
Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ... by
Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ...Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ...
Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ...ShapeBlue
85 views10 slides
Business Analyst Series 2023 - Week 4 Session 7 by
Business Analyst Series 2023 -  Week 4 Session 7Business Analyst Series 2023 -  Week 4 Session 7
Business Analyst Series 2023 - Week 4 Session 7DianaGray10
126 views31 slides
Confidence in CloudStack - Aron Wagner, Nathan Gleason - Americ by
Confidence in CloudStack - Aron Wagner, Nathan Gleason - AmericConfidence in CloudStack - Aron Wagner, Nathan Gleason - Americ
Confidence in CloudStack - Aron Wagner, Nathan Gleason - AmericShapeBlue
88 views9 slides
Microsoft Power Platform.pptx by
Microsoft Power Platform.pptxMicrosoft Power Platform.pptx
Microsoft Power Platform.pptxUni Systems S.M.S.A.
80 views38 slides

Recently uploaded(20)

Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue by ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlueElevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
Elevating Privacy and Security in CloudStack - Boris Stoyanov - ShapeBlue
ShapeBlue179 views
DRBD Deep Dive - Philipp Reisner - LINBIT by ShapeBlue
DRBD Deep Dive - Philipp Reisner - LINBITDRBD Deep Dive - Philipp Reisner - LINBIT
DRBD Deep Dive - Philipp Reisner - LINBIT
ShapeBlue140 views
Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ... by ShapeBlue
Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ...Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ...
Live Demo Showcase: Unveiling Dell PowerFlex’s IaaS Capabilities with Apache ...
ShapeBlue85 views
Business Analyst Series 2023 - Week 4 Session 7 by DianaGray10
Business Analyst Series 2023 -  Week 4 Session 7Business Analyst Series 2023 -  Week 4 Session 7
Business Analyst Series 2023 - Week 4 Session 7
DianaGray10126 views
Confidence in CloudStack - Aron Wagner, Nathan Gleason - Americ by ShapeBlue
Confidence in CloudStack - Aron Wagner, Nathan Gleason - AmericConfidence in CloudStack - Aron Wagner, Nathan Gleason - Americ
Confidence in CloudStack - Aron Wagner, Nathan Gleason - Americ
ShapeBlue88 views
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava... by ShapeBlue
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...
Centralized Logging Feature in CloudStack using ELK and Grafana - Kiran Chava...
ShapeBlue101 views
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T by ShapeBlue
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&TCloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T
CloudStack and GitOps at Enterprise Scale - Alex Dometrius, Rene Glover - AT&T
ShapeBlue112 views
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ... by ShapeBlue
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...
Import Export Virtual Machine for KVM Hypervisor - Ayush Pandey - University ...
ShapeBlue79 views
"Surviving highload with Node.js", Andrii Shumada by Fwdays
"Surviving highload with Node.js", Andrii Shumada "Surviving highload with Node.js", Andrii Shumada
"Surviving highload with Node.js", Andrii Shumada
Fwdays53 views
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue by ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlueVNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
VNF Integration and Support in CloudStack - Wei Zhou - ShapeBlue
ShapeBlue163 views
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti... by ShapeBlue
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
DRaaS using Snapshot copy and destination selection (DRaaS) - Alexandre Matti...
ShapeBlue98 views
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online by ShapeBlue
KVM Security Groups Under the Hood - Wido den Hollander - Your.OnlineKVM Security Groups Under the Hood - Wido den Hollander - Your.Online
KVM Security Groups Under the Hood - Wido den Hollander - Your.Online
ShapeBlue181 views
State of the Union - Rohit Yadav - Apache CloudStack by ShapeBlue
State of the Union - Rohit Yadav - Apache CloudStackState of the Union - Rohit Yadav - Apache CloudStack
State of the Union - Rohit Yadav - Apache CloudStack
ShapeBlue253 views
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha... by ShapeBlue
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...
Mitigating Common CloudStack Instance Deployment Failures - Jithin Raju - Sha...
ShapeBlue138 views
Future of AR - Facebook Presentation by Rob McCarty
Future of AR - Facebook PresentationFuture of AR - Facebook Presentation
Future of AR - Facebook Presentation
Rob McCarty62 views
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda... by ShapeBlue
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
Hypervisor Agnostic DRS in CloudStack - Brief overview & demo - Vishesh Jinda...
ShapeBlue120 views

Offline strategies for HTML5 web applications - ConFoo13

  • 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
  • 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
  • 13. Offline strategies for HTML5 web applications What does „offline“ mean?
  • 14. Offline strategies for HTML5 web applications What does „offline“ mean? Application vs. Content
  • 15. Offline strategies for HTML5 web applications What does „offline“ mean? Application Cache vs. Offline Storage
  • 16. Offline strategies for HTML5 web applications App Cache for caching static resources HTML Page: <!DOCTYPE html> <html lang="en">
  • 17. Offline strategies for HTML5 web applications App Cache for caching static resources HTML Page: <!DOCTYPE html> <html lang="en" manifest="cache.manifest"> cache.manifest (served with Content-Type: text/cache-manifest): CACHE MANIFEST js/app.js css/app.css favicon.ico http://someotherdomain.com/image.png
  • 18. Offline strategies for HTML5 web applications App Cache for caching static resources CACHE MANIFEST # 2012­09­16 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. Offline strategies for HTML5 web applications App Cache for caching static resources CACHE MANIFEST # 2012­09­16 FALLBACK: / /offline.html NETWORK: *
  • 20. Offline strategies for HTML5 web applications App Cache Scripting // events fired by window.applicationCache window.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 file window.applicationCache.onprogress = function(e) {   log("Progress: downloaded file " + counter);   counter++; };
  • 21. Offline strategies for HTML5 web applications App Cache Scripting // 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 didn't change...     }   }, false); }, false);
  • 22. Offline strategies for HTML5 web applications App Cache – Some gotchas!
  • 23. Offline strategies for HTML5 web applications App Cache – Some gotchas! 1. Files are always(!) served from the application cache.
  • 24. Offline strategies for HTML5 web applications App Cache – Some gotchas! 2. The application cache only updates if the content of the manifest itself has changed!
  • 25. Offline strategies for HTML5 web applications App Cache – Some gotchas! 3. If any of the files listed in the CACHE section can't be retrieved, the entire cache will be disregarded.
  • 26. Offline strategies for HTML5 web applications App Cache – Some gotchas! 4. If the manifest file itself can't be retrieved, the cache will ignored!
  • 27. Offline strategies for HTML5 web applications App Cache – Some gotchas! 5. Non-cached resources will not load on a cached page!
  • 28. Offline strategies for HTML5 web applications App Cache – Some gotchas! 6. The page needs to be reloaded, otherwise the new resources do not show up!
  • 29. Offline strategies for HTML5 web applications App Cache – Some gotchas! 7. To avoid the risk of caching manifest files set expires headers!
  • 30. Offline strategies for HTML5 web applications App Cache – What to cache? Yes: No:  Fonts  CSS  Splash image  HTML  App icon  Javascript  Entry page  Fallback bootstrap
  • 31. Offline strategies for HTML5 web applications App Cache – What to cache? Use the App Cache only for „static content“.
  • 32. Offline strategies for HTML5 web applications The Data URI scheme
  • 33. Offline strategies for HTML5 web applications The Data URI scheme <!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,iVBORw0KGgoAAAANSUhEUgAAAAUAAA AFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAA O9TXL0Y4OHwAAAABJRU5ErkJggg==') no­repeat scroll left  top; }   </style>  </head>  <body>   <img  src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAA AFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAA O9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">  </body> </html>
  • 34. Offline strategies for HTML5 web applications Storing dynamic data locally (in HTML5)
  • 36. Offline strategies for HTML5 web applications Storing dynamic data locally (in HTML5) Find the sources here: github.com/bitExpert/html5-offline
  • 37. Offline strategies for HTML5 web applications Storing dynamic data locally (in HTML5) Web Storage, Web SQL Database, IndexedDB, File API
  • 38. Offline strategies for HTML5 web applications Web Storage
  • 39. Offline strategies for HTML5 web applications Web Storage Very convenient form of offline storage: simple key-value store
  • 40. Offline strategies for HTML5 web applications Web Storage: 2 different types localStorage vs. sessionStorage
  • 41. Offline strategies for HTML5 web applications Web Storage: Add item 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); } }
  • 42. Offline strategies for HTML5 web applications Web Storage: Modify item function modify(item) { try { // store object as string localStorage.setItem(item.id,               JSON.stringify(item)          ); } catch(ex) { console.log(ex); } }
  • 43. Offline strategies for HTML5 web applications Web Storage: Remove item function remove (id) { try { localStorage.removeItem(id); } catch(ex) { console.log(ex); } }
  • 44. Offline strategies for HTML5 web applications Web Storage: Read items 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);       } }
  • 45. Offline strategies for HTML5 web applications Web Storage: What about sessionStorage?
  • 46. Offline strategies for HTML5 web applications Web Storage: What about sessionStorage? Replace „localStorage „ with „sessionStorage“
  • 47. Offline strategies for HTML5 web applications Web Storage: Add item to sessionStorage 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 sessionStorage.setItem(item.id,               JSON.stringify(item)          ); // update the index set_lastIndex(item.id); } catch(ex) { console.log(ex); } }
  • 48. Offline strategies for HTML5 web applications Web Storage: Don`t like method calls? var value = "my value"; // method call localStorage.setItem("key", value); // Array accessor localStorage[key] = value; // Property accessor localStorage.key = value;
  • 50. Offline strategies for HTML5 web applications Web Storage: Pro Most compatible format up to now.
  • 51. Offline strategies for HTML5 web applications Web Storage: Con The data is not structured.
  • 52. Offline strategies for HTML5 web applications Web Storage: Con No transaction support!
  • 53. Offline strategies for HTML5 web applications Web Storage: Con Lack of automatically expiring storage.
  • 54. Offline strategies for HTML5 web applications Web Storage: Con Inadequate information about storage quota.
  • 55. Offline strategies for HTML5 web applications Web SQL Database
  • 56. Offline strategies for HTML5 web applications Web SQL Database An offline SQL database based on SQLite, an general-purpose SQL engine.
  • 57. Offline strategies for HTML5 web applications Web SQL Database: Callback methods 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)); } };
  • 58. Offline strategies for HTML5 web applications Web SQL Database: Setup Database // 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 ); });
  • 59. Offline strategies for HTML5 web applications Web SQL Database: Add item function add(item) { db.transaction(function(tx) { tx.executeSql( 'INSERT INTO todo (todo) VALUES (?)', [ item.todo ], onSuccess, onError ); }); }
  • 60. Offline strategies for HTML5 web applications Web SQL Database: Modify item function modify(item) { db.transaction(function(tx) { tx.executeSql( 'UPDATE todo SET todo = ? WHERE id = ?', [ item.todo item.id ], onSuccess, onError ); }); }
  • 61. Offline strategies for HTML5 web applications Web SQL Database: Remove item function remove(id) { db.transaction(function (tx) { tx.executeSql( 'DELETE FROM todo WHERE id = ?', [ id ], onSuccess, onError ); }); }
  • 62. Offline strategies for HTML5 web applications Web SQL Database: Read items function read() { db.transaction(function (tx) { tx.executeSql( 'SELECT * FROM todo', [], onSuccess, onError ); }); }
  • 63. Offline strategies for HTML5 web applications Web SQL Database: Pro It`s a SQL database within the browser!
  • 64. Offline strategies for HTML5 web applications Web SQL Database: Con It`s a SQL database within the browser!
  • 65. Offline strategies for HTML5 web applications Web SQL Database: Con SQLite is slooooow!
  • 66. Offline strategies for HTML5 web applications Web SQL Database: Con The specification is no longer part of HTML5!
  • 67. Offline strategies for HTML5 web applications IndexedDB
  • 68. Offline strategies for HTML5 web applications IndexedDB A nice compromise between Web Storage and Web SQL Database giving you the best of both worlds.
  • 69. Offline strategies for HTML5 web applications Web SQL Database vs. IndexedDB Category Web SQL IndexedDB Location Tables contain columns and objectStore contains Javascript objects and rows keys Query SQL Cursor APIs, Key Range APIs, and Mechanism Application Code Transaction Lock can happen on Lock can happen on database databases, tables, or rows VERSION_CHANGE transaction, on an on READ_WRITE objectStore READ_ONLY and transactions READ_WRITE transactions. Transaction Transaction creation is Transaction creation is explicit. Default is to Commits explicit. Default is to rollback commit unless we call abort or there is an unless we call commit. error that is not caught.
  • 70. Offline strategies for HTML5 web applications IndexedDB: Preparation // 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;
  • 71. Offline strategies for HTML5 web applications IndexedDB: Create object store 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() {}; }; } };
  • 72. Offline strategies for HTML5 web applications IndexedDB: Add item 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); } }
  • 73. Offline strategies for HTML5 web applications IndexedDB: Modify item 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); } }
  • 74. Offline strategies for HTML5 web applications IndexedDB: Remove item 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); } }
  • 75. Offline strategies for HTML5 web applications IndexedDB: Read items 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); } }
  • 76. Offline strategies for HTML5 web applications File API
  • 77. Offline strategies for HTML5 web applications File API FileReader API and FileWriter API
  • 78. Offline strategies for HTML5 web applications File API: Preparations 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); };
  • 79. Offline strategies for HTML5 web applications File API: Preparations // 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
  • 80. Offline strategies for HTML5 web applications File API: Requesting quota // request quota for persistent store window.webkitStorageInfo.requestQuota( PERSISTENT, size, function(grantedBytes) { window.requestFileSystem( PERSISTENT, grantedBytes, function(fs) { // @TODO: access filesystem } } } }
  • 81. Offline strategies for HTML5 web applications
  • 82. Offline strategies for HTML5 web applications File API: Add item function add(item) {   window.webkitStorageInfo.requestQuota(   PERSISTENT,   size,   function(grantedBytes) {   window.requestFileSystem(   PERSISTENT,   grantedBytes,   function(fs){   writeToFile(fs, item);   },   onError   );   },   function(e) {   onError(e);   }   );   },
  • 83. Offline strategies for HTML5 web applications File API: Add item 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 ); };
  • 84. Offline strategies for HTML5 web applications File API: Read items function read() {   window.webkitStorageInfo.requestQuota(   PERSISTENT,   size,   function(grantedBytes) {   window.requestFileSystem(   PERSISTENT,   grantedBytes,   function(fs){   readFromFile(fs);   },   onError   );   },   function(e) {   onError(e);   }   ); }
  • 85. Offline strategies for HTML5 web applications File API: Read items 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 ); }
  • 86. Offline strategies for HTML5 web applications Am I online?
  • 87. Offline strategies for HTML5 web applications Am I online? document.body.addEventListener("online", function () {   // browser is online! } document.body.addEventListener("offline", function () {   // browser is not online! }
  • 88. Offline strategies for HTML5 web applications Am I online? Another approach... $.ajax({   dataType: 'json',   url: 'http://myappurl.com/ping',   success: function(data){     // ping worked   },   error: function() {     // ping failed ­> Server not reachable   } });
  • 89. Offline strategies for HTML5 web applications Browser support? App Cache Web Storage WebSQL IndexedDB File API Data URI IE 10.0 8.0 10.0 10.0 - 8.0* Firefox 11.0 11.0 11.0 11.0 19.0 16.0 Chrome 18.0 18.0 18.0 18.0 18.0 18.0 Safari 5.1 5.1 5.1 - - 5.1 Opera 12.1 12.1 12.1 - - 12.1 iOS Safari 3.2 3.2 3.2 - - 3.2 Android 2.1 2.1 2.1 - - 2.1 Source: http://caniuse.com
  • 90. Offline strategies for HTML5 web applications Storage limitations?
  • 91. Offline strategies for HTML5 web applications Storage limitations? All storage technologies are limited by quotas. Be aware of what you do!
  • 92. Offline strategies for HTML5 web applications Storage limitations? 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