SlideShare a Scribd company logo
Offline strategies for
HTML5 web applications
Stephan Hochdörfer, bitExpert AG
Offline strategies for HTML5 web applications

 About me

  Stephan Hochdörfer, bitExpert AG

  Department Manager Research Labs

  enjoying PHP since 1999

  S.Hochdoerfer@bitExpert.de

  @shochdoerfer
Offline strategies for HTML5 web applications - pfCongres2012
Offline strategies for HTML5 web applications - pfCongres2012
Offline strategies for HTML5 web applications - pfCongres2012
Offline strategies for HTML5 web applications - pfCongres2012
Offline strategies for HTML5 web applications - pfCongres2012
Offline strategies for HTML5 web applications - pfCongres2012
Offline strategies for HTML5 web applications - pfCongres2012
Offline strategies for HTML5 web applications - pfCongres2012
Offline strategies for HTML5 web applications - pfCongres2012
Offline strategies for HTML5 web applications - pfCongres2012
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

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

 What does „offline“ mean?




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

 Application Cache for static resources
 <!­­ clock.html ­­>
 <!DOCTYPE HTML>
 <html>
  <head>
   <title>Clock</title>
   <script src="clock.js"></script>
   <link rel="stylesheet" href="clock.css">
  </head>
  <body>
   <p>The time is: <output id="clock"></output></p>
  </body>
 </html>

 /* clock.css */
 output { font: 2em sans­serif; }

 /* clock.js */
 setTimeout(function () {
     document.getElementById('clock').value = new Date();
 }, 1000);
Offline strategies for HTML5 web applications

 Application Cache for static resources

 cache.manifest - must be served using the text/cache-manifest
 MIME type.

 CACHE MANIFEST
 # 2012­09­16
 clock.html
 clock.css
 clock.js
Offline strategies for HTML5 web applications

 Application Cache for static resources
 <!­­ clock.html ­­>
 <!DOCTYPE HTML>
 <html manifest="cache.manifest">
  <head>
   <title>Clock</title>
   <script src="clock.js"></script>
   <link rel="stylesheet" href="clock.css">
  </head>
  <body>
   <p>The time is: <output id="clock"></output></p>
  </body>
 </html>
Offline strategies for HTML5 web applications

 Application Cache for 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

 Application Cache for static resources
 CACHE MANIFEST
 # 2012­09­16

 FALLBACK:
 / /offline.html

 NETWORK:
 *
Offline strategies for HTML5 web applications

 Scripting the Application Cache
 // 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

 Scripting the Application Cache
 // 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 changed.
     }
   }, false);

 }, false);
Offline strategies for HTML5 web applications

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

 Application Cache – Some gotchas!




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

 Application Cache – Some gotchas!




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

 Application 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

 Application Cache – Some gotchas!




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

 Application Cache – Some gotchas!




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

 Application Cache – Some gotchas!




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

 Application Cache – Some gotchas!




      7. To avoid the risk of caching
     manifest files set expires headers!
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

 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: localStorage example
 var myVar = 123;
 var myObj = {name: "Stephan"};

 // write scalar value to localStorage
 localStorage['myVar'] = myVar;

 // read scalar value from localStorage
 myVar = localStorage['myVar'];

 // write object to localStorage
 localStorage['myObj'] = JSON.stringify(myObj);

 // read object from localStorage
 myObj = JSON.parse(localStorage['myObj']);
Offline strategies for HTML5 web applications

 Web Storage: sessionStorage example
 var myVar = 123;
 var myObj = {name: "Stephan"};

 // write scalar value to sessionStorage
 sessionStorage['myVar'] = myVar;

 // read scalar value from sessionStorage
 myVar = sessionStorage['myVar'];

 // write object to sessionStorage
 sessionStorage['myObj'] = JSON.stringify(myObj);

 // read object from sessionStorage
 myObj = JSON.parse(sessionStorage['myObj']);
Offline strategies for HTML5 web applications

 Web Storage: Does my browser support it?
 function supports_local_storage() {
   try {
     return 'localStorage' in window &&     
           window['localStorage'] !== null;
   } catch(e){
     return false;
   }
 }
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 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
 function prepareDatabase(ready, error) {
   return openDatabase('documents', '1.0', 
     'Offline document storage', 5*1024*1024, function 
 (db) {
     db.changeVersion('', '1.0', function (t) {
       t.executeSql('CREATE TABLE docids (id, name)');
     }, error);
   });
 }

 function showDocCount(db, span) {
   db.readTransaction(function (t) {
     t.executeSql('SELECT COUNT(*) AS c FROM docids', [], 
       function (t, r) {
          span.textContent = r.rows[0].c;
       }, function (t, e) {
          // couldn't read database
          span.textContent = '(unknown: ' + e.message + 
 ')';
     });
   });
 }
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 – Creating an ObjectStore
 indexedDB.open = function() {
   var request = indexedDB.open("todos");
   request.onsuccess = function(e) {
     var v = "2.0 beta";
     todoDB.indexedDB.db = e.target.result;
     var db = todoDB.indexedDB.db;
     if (v!= db.version) {
       var setVrequest = db.setVersion(v);
       setVrequest.onfailure = todoDB.indexedDB.onerror;
       setVrequest.onsuccess = function(e) {
         if (db.objectStoreNames.contains("todo")) {
           db.deleteObjectStore("todo");
         }
         var store = db.createObjectStore("todo", 
 {keyPath: "timeStamp"});
         todoDB.indexedDB.getAllTodoItems();
       };
     } else {
       todoDB.indexedDB.getAllTodoItems();
     }
   };
   request.onfailure = todoDB.indexedDB.onerror;
 };
Offline strategies for HTML5 web applications

 IndexedDB – Adding data to ObjectStore
 indexedDB.addTodo = function() {
   var db = todoDB.indexedDB.db;
   var trans = db.transaction(['todo'], 
 IDBTransaction.READ_WRITE);
   var store = trans.objectStore('todo');

   var data = {
     "text": todoText,
     "timeStamp": new Date().getTime()
   };

   var request = store.put(data);
   request.onsuccess = function(e) {
     todoDB.indexedDB.getAllTodoItems();
   };
   request.onerror = function(e) {
     console.log("Failed adding items due to: ", e);
   };
 };
Offline strategies for HTML5 web applications

 IndexedDB – Retrieving data
 function show() {
   var request = window.indexedDB.open("todos");
   request.onsuccess = function(event) {
     var db = todoDB.indexedDB.db;
     var trans = db.transaction(["todo"], 
 IDBTransaction.READ_ONLY);
     var request = trans.objectStore("todo").openCursor();
     var ul = document.createElement("ul");

     request.onsuccess = function(event) {
       var cursor = request.result || event.result;
       // If cursor is null, enumeration completed
       if(!cursor) {
         document.getElementById("todos").appendChild(ul);
         return;
       }

       var li = document.createElement("li");
       li.textContent = cursor.value.text;
       ul.appendChild(li);
       cursor.continue();
     }
   }
 }
Offline strategies for HTML5 web applications

 IndexedDB – Deleting data
 indexedDB.deleteTodo = function(id, text) {
   var db = todoDB.indexedDB.db;
   var trans = db.transaction(["todo"], 
 IDBTransaction.READ_WRITE);
   var store = trans.objectStore("todo");

   var request = store.delete(id);
   request.onsuccess = function(e) {
     todoDB.indexedDB.getAllTodoItems();
   };
   request.onerror = function(e) {
     console.log("Error Adding: ", e);
   };
 };
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 – Requesting access
 function onInitFs(fs) {
   console.log('Opened file system: ' + fs.name);
 }

 function errorHandler(e) {
   console.log('Error: ' + e.code);
 }

 window.requestFileSystem(window.TEMPORARY, 5*1024*1024 
 /*5MB*/, onInitFs, errorHandler);
Offline strategies for HTML5 web applications

 File API – Requesting quota
 window.webkitStorageInfo.requestQuota(
     PERSISTENT, 
     5*1024*1024 /*5MB*/, 
     function(grantedBytes) {
       window.requestFileSystem(PERSISTENT, grantedBytes, 
          onInitFs, errorHandler);
     }, 
     function(e) {
       console.log('Error', e);
 });
Offline strategies for HTML5 web applications
Offline strategies for HTML5 web applications

 File API – Creating a file
 function onInitFs(fs) {
   fs.root.getFile('log.txt', 
   {create: true, exclusive: true}, 
   function(fileEntry) {
     // fileEntry.name == 'log.txt'
     // fileEntry.fullPath == '/log.txt'
   }, errorHandler);
 }

 window.requestFileSystem(window.TEMPORARY, 5*1024*1024 
 /*5MB*/, onInitFs, errorHandler);
Offline strategies for HTML5 web applications

 File API – Reading a file
 function onInitFs(fs) {
   fs.root.getFile('log.txt', {}, 
   function(fileEntry) {
     fileEntry.file(function(file) {
        var reader = new FileReader();

        reader.onloadend = function(e) {
          var txtArea   = 
               document.createElement('textarea');
          txtArea.value = this.result;
          document.body.appendChild(txtArea);
        };
        reader.readAsText(file);
     }, errorHandler);
   }, errorHandler);
 }

 window.requestFileSystem(window.TEMPORARY, 5*1024*1024 
 /*5MB*/, onInitFs, errorHandler);
Offline strategies for HTML5 web applications

 File API – Writing to a file
 function onInitFs(fs) {
   fs.root.getFile('log.txt', {create: true}, 
   function(fileEntry) {
     fileEntry.createWriter(function(fileWriter) {

       fileWriter.onwriteend = function(e) {
         console.log('Write completed.');
       };
       fileWriter.onerror = function(e) {
         console.log('Write failed: ' + e.toString());
       };

       var bb = new BlobBuilder();
       bb.append('Lorem Ipsum');
       fileWriter.write(bb.getBlob('text/plain'));
     }, errorHandler);
   }, errorHandler);
 }

 window.requestFileSystem(window.TEMPORARY, 5*1024*1024 
 /*5MB*/, onInitFs, errorHandler);
Offline strategies for HTML5 web applications

 File API – Appending data to a file
 function onInitFs(fs) {
   fs.root.getFile('log.txt', {create: false}, 
   function(fileEntry) {
     fileEntry.createWriter(function(fileWriter) {

       fileWriter.seek(fileWriter.length);

       var bb = new BlobBuilder();
       bb.append('Hello World');
       fileWriter.write(bb.getBlob('text/plain'));
     }, errorHandler);
   }, errorHandler);
 }

 window.requestFileSystem(window.TEMPORARY, 5*1024*1024 
 /*5MB*/, onInitFs, errorHandler);
Offline strategies for HTML5 web applications

 File API – Deleting a file
 function onInitFs(fs) {
   fs.root.getFile('log.txt', {create: false}, 
   function(fileEntry) {
     fileEntry.remove(function() {
       console.log('File removed.');
     }, errorHandler);
    }, errorHandler);
 }

 window.requestFileSystem(window.TEMPORARY, 5*1024*1024 
 /*5MB*/, onInitFs, errorHandler);
Offline strategies for HTML5 web applications

 File API – Creating directories
 function onInitFs(fs) {
    fs.root.getDirectory('MyFolder', {create: true}, 
    function(dirEntry) {
     // do stuff...
     }, errorHandler);
 }

 window.requestFileSystem(window.TEMPORARY, 5*1024*1024 
 /*5MB*/, onInitFs, errorHandler);
Offline strategies for HTML5 web applications - pfCongres2012
Offline strategies for HTML5 web applications

 File API – Browser support?




             Up to now: Chrome only
Offline strategies for HTML5 web applications

 File API – Browser support?




                But: idb.filesystem.js
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 - pfCongres2012
Thank you!
http://joind.in/7073

More Related Content

PDF
Offline Strategies for HTML5 Web Applications - ipc13
PDF
Offline strategies for HTML5 web applications - ConFoo13
PDF
Offline strategies for HTML5 web applications - IPC12
PDF
Offline Strategies for HTML5 Web Applications - oscon13
PDF
Offline strategies for HTML5 web applications - frOSCon8
PPTX
HTML5 Gaming Payment Platforms
PPT
How Hadoop Revolutionized Data Warehousing at Yahoo and Facebook
PDF
Introduction to JavaScript for APEX Developers - Module 1: JavaScript Basics
Offline Strategies for HTML5 Web Applications - ipc13
Offline strategies for HTML5 web applications - ConFoo13
Offline strategies for HTML5 web applications - IPC12
Offline Strategies for HTML5 Web Applications - oscon13
Offline strategies for HTML5 web applications - frOSCon8
HTML5 Gaming Payment Platforms
How Hadoop Revolutionized Data Warehousing at Yahoo and Facebook
Introduction to JavaScript for APEX Developers - Module 1: JavaScript Basics

What's hot (20)

PPTX
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
PDF
Module 3: Working with the DOM and jQuery
PPTX
Migration from Legacy CMS to Drupal
PDF
PPT
Xml http request
PPTX
Rohit&kunjan
PPTX
REST Api Tips and Tricks
PPTX
RDF Validation in a Linked Data World - A vision beyond structural and value ...
KEY
Open Standards for the Semantic Web: XML / RDF(S) / OWL / SOAP
PDF
Apache Olingo - ApacheCon Denver 2014
PDF
Galaxy
PDF
Evolving Hadoop into an Operational Platform with Data Applications
PDF
Interoperable Ajax Tools And Mashups Ferraiolo
PDF
Talend Open Studio Fundamentals #1: Workspaces, Jobs, Metadata and Trips & Tr...
PDF
OTN TOUR 2016 - Oracle Database 12c - The Best Oracle Database 12c Tuning Fea...
PDF
112815 java ee8_davidd
PPT
Stop Making The Web Harder Than It Is; Real-world REST, HATEOAS, and Hypermed...
PPTX
Biwa summit 2015 oaa oracle data miner hands on lab
PDF
JSON and Oracle Database: A Brave New World
PPT
Stat 5.4 Pre Sales Demo Master
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
Module 3: Working with the DOM and jQuery
Migration from Legacy CMS to Drupal
Xml http request
Rohit&kunjan
REST Api Tips and Tricks
RDF Validation in a Linked Data World - A vision beyond structural and value ...
Open Standards for the Semantic Web: XML / RDF(S) / OWL / SOAP
Apache Olingo - ApacheCon Denver 2014
Galaxy
Evolving Hadoop into an Operational Platform with Data Applications
Interoperable Ajax Tools And Mashups Ferraiolo
Talend Open Studio Fundamentals #1: Workspaces, Jobs, Metadata and Trips & Tr...
OTN TOUR 2016 - Oracle Database 12c - The Best Oracle Database 12c Tuning Fea...
112815 java ee8_davidd
Stop Making The Web Harder Than It Is; Real-world REST, HATEOAS, and Hypermed...
Biwa summit 2015 oaa oracle data miner hands on lab
JSON and Oracle Database: A Brave New World
Stat 5.4 Pre Sales Demo Master
Ad

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

PDF
Attractive HTML5~開発者の視点から~
PPTX
PDF
Making Of PHP Based Web Application
PPTX
The current status of html5 technology and standard
PDF
Familiar HTML5 - 事例とサンプルコードから学ぶ 身近で普通に使わているHTML5
PPT
Introduction To Code Igniter
PPTX
HTML5 on Mobile
KEY
Taking your Web App for a walk
PPTX
SAS_Forum_2015_Data_Visualisation_With_HighCharts_D3
PPTX
Html5 and web technology update
PDF
It is not HTML5. but ... / HTML5ではないサイトからHTML5を考える
ODP
Html5
PPT
Developing Java Web Applications
PPTX
Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012
KEY
WHAT IS HTML5? (at CSS Nite Osaka)
KEY
HTML5 Hacking - Yahoo! Open Hack Day
KEY
PDF
Introduction to HTML5
PPT
Html5 drupal7 with mandakini kumari(1)
PPTX
web development 7.pptx
Attractive HTML5~開発者の視点から~
Making Of PHP Based Web Application
The current status of html5 technology and standard
Familiar HTML5 - 事例とサンプルコードから学ぶ 身近で普通に使わているHTML5
Introduction To Code Igniter
HTML5 on Mobile
Taking your Web App for a walk
SAS_Forum_2015_Data_Visualisation_With_HighCharts_D3
Html5 and web technology update
It is not HTML5. but ... / HTML5ではないサイトからHTML5を考える
Html5
Developing Java Web Applications
Oracle Application Express & jQuery Mobile - OGh Apex Dag 2012
WHAT IS HTML5? (at CSS Nite Osaka)
HTML5 Hacking - Yahoo! Open Hack Day
Introduction to HTML5
Html5 drupal7 with mandakini kumari(1)
web development 7.pptx
Ad

More from Stephan Hochdörfer (20)

PDF
Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...
PDF
Phing for power users - frOSCon8
PDF
Real World Dependency Injection - oscon13
PDF
Dependency Injection in PHP - dwx13
PDF
Offline Strategien für HTML5 Web Applikationen - dwx13
PDF
Your Business. Your Language. Your Code - dpc13
PDF
Phing for power users - dpc_uncon13
PDF
Offline-Strategien für HTML5 Web Applikationen - wmka
PDF
Offline-Strategien für HTML5 Web Applikationen - bedcon13
PDF
Real World Dependency Injection - phpugffm13
PDF
Testing untestable code - ConFoo13
PDF
A Phing fairy tale - ConFoo13
PDF
Offline-Strategien für HTML5Web Applikationen - WMMRN12
PDF
Testing untestable code - IPC12
PDF
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
PDF
Wie Software-Generatoren die Welt verändern können - Herbstcampus12
PDF
Testing untestable code - Herbstcampus12
PDF
Testing untestable code - oscon 2012
PDF
Introducing a Software Generator Framework - JAZOON12
PDF
The state of DI - DPC12
Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...
Phing for power users - frOSCon8
Real World Dependency Injection - oscon13
Dependency Injection in PHP - dwx13
Offline Strategien für HTML5 Web Applikationen - dwx13
Your Business. Your Language. Your Code - dpc13
Phing for power users - dpc_uncon13
Offline-Strategien für HTML5 Web Applikationen - wmka
Offline-Strategien für HTML5 Web Applikationen - bedcon13
Real World Dependency Injection - phpugffm13
Testing untestable code - ConFoo13
A Phing fairy tale - ConFoo13
Offline-Strategien für HTML5Web Applikationen - WMMRN12
Testing untestable code - IPC12
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
Wie Software-Generatoren die Welt verändern können - Herbstcampus12
Testing untestable code - Herbstcampus12
Testing untestable code - oscon 2012
Introducing a Software Generator Framework - JAZOON12
The state of DI - DPC12

Recently uploaded (20)

PDF
Encapsulation theory and applications.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
KodekX | Application Modernization Development
PDF
Unlocking AI with Model Context Protocol (MCP)
PPT
Teaching material agriculture food technology
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
Understanding_Digital_Forensics_Presentation.pptx
Encapsulation theory and applications.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Chapter 3 Spatial Domain Image Processing.pdf
Approach and Philosophy of On baking technology
Review of recent advances in non-invasive hemoglobin estimation
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Electronic commerce courselecture one. Pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
KodekX | Application Modernization Development
Unlocking AI with Model Context Protocol (MCP)
Teaching material agriculture food technology
Programs and apps: productivity, graphics, security and other tools
Spectral efficient network and resource selection model in 5G networks
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
MYSQL Presentation for SQL database connectivity
Understanding_Digital_Forensics_Presentation.pptx

Offline strategies for HTML5 web applications - pfCongres2012

  • 1. Offline strategies for HTML5 web applications Stephan Hochdörfer, bitExpert AG
  • 2. Offline strategies for HTML5 web applications About me  Stephan Hochdörfer, bitExpert AG  Department Manager Research Labs  enjoying PHP since 1999  S.Hochdoerfer@bitExpert.de  @shochdoerfer
  • 13. 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
  • 14. Offline strategies for HTML5 web applications What does „offline“ mean?
  • 15. Offline strategies for HTML5 web applications What does „offline“ mean? Application Cache vs. Offline Storage
  • 16. Offline strategies for HTML5 web applications Application Cache for static resources <!­­ clock.html ­­> <!DOCTYPE HTML> <html>  <head>   <title>Clock</title>   <script src="clock.js"></script>   <link rel="stylesheet" href="clock.css">  </head>  <body>   <p>The time is: <output id="clock"></output></p>  </body> </html> /* clock.css */ output { font: 2em sans­serif; } /* clock.js */ setTimeout(function () {     document.getElementById('clock').value = new Date(); }, 1000);
  • 17. Offline strategies for HTML5 web applications Application Cache for static resources cache.manifest - must be served using the text/cache-manifest MIME type. CACHE MANIFEST # 2012­09­16 clock.html clock.css clock.js
  • 18. Offline strategies for HTML5 web applications Application Cache for static resources <!­­ clock.html ­­> <!DOCTYPE HTML> <html manifest="cache.manifest">  <head>   <title>Clock</title>   <script src="clock.js"></script>   <link rel="stylesheet" href="clock.css">  </head>  <body>   <p>The time is: <output id="clock"></output></p>  </body> </html>
  • 19. Offline strategies for HTML5 web applications Application Cache for 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
  • 20. Offline strategies for HTML5 web applications Application Cache for static resources CACHE MANIFEST # 2012­09­16 FALLBACK: / /offline.html NETWORK: *
  • 21. Offline strategies for HTML5 web applications Scripting the Application Cache // 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++; };
  • 22. Offline strategies for HTML5 web applications Scripting the Application Cache // 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 changed.     }   }, false); }, false);
  • 23. Offline strategies for HTML5 web applications Application Cache – Some gotchas!
  • 24. Offline strategies for HTML5 web applications Application Cache – Some gotchas! 1. Files are always(!) served from the application cache.
  • 25. Offline strategies for HTML5 web applications Application Cache – Some gotchas! 2. The application cache only updates if the content of the manifest itself has changed!
  • 26. Offline strategies for HTML5 web applications Application Cache – Some gotchas! 3. If any of the files listed in the CACHE section can't be retrieved, the entire cache will be disregarded.
  • 27. Offline strategies for HTML5 web applications Application Cache – Some gotchas! 4. If the manifest file itself can't be retrieved, the cache will ignored!
  • 28. Offline strategies for HTML5 web applications Application Cache – Some gotchas! 5. Non-cached resources will not load on a cached page!
  • 29. Offline strategies for HTML5 web applications Application Cache – Some gotchas! 6. The page needs to be reloaded, otherwise the new resources do not show up!
  • 30. Offline strategies for HTML5 web applications Application Cache – Some gotchas! 7. To avoid the risk of caching manifest files set expires headers!
  • 31. Offline strategies for HTML5 web applications The Data URI scheme
  • 32. 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>
  • 33. Offline strategies for HTML5 web applications Storing dynamic data locally (in HTML5)
  • 34. Offline strategies for HTML5 web applications Storing dynamic data locally (in HTML5) Web Storage, Web SQL Database, IndexedDB, File API
  • 35. Offline strategies for HTML5 web applications Web Storage
  • 36. Offline strategies for HTML5 web applications Web Storage Very convenient form of offline storage: simple key-value store
  • 37. Offline strategies for HTML5 web applications Web Storage: 2 different types localStorage vs. sessionStorage
  • 38. Offline strategies for HTML5 web applications Web Storage: localStorage example var myVar = 123; var myObj = {name: "Stephan"}; // write scalar value to localStorage localStorage['myVar'] = myVar; // read scalar value from localStorage myVar = localStorage['myVar']; // write object to localStorage localStorage['myObj'] = JSON.stringify(myObj); // read object from localStorage myObj = JSON.parse(localStorage['myObj']);
  • 39. Offline strategies for HTML5 web applications Web Storage: sessionStorage example var myVar = 123; var myObj = {name: "Stephan"}; // write scalar value to sessionStorage sessionStorage['myVar'] = myVar; // read scalar value from sessionStorage myVar = sessionStorage['myVar']; // write object to sessionStorage sessionStorage['myObj'] = JSON.stringify(myObj); // read object from sessionStorage myObj = JSON.parse(sessionStorage['myObj']);
  • 40. Offline strategies for HTML5 web applications Web Storage: Does my browser support it? function supports_local_storage() {   try {     return 'localStorage' in window &&                window['localStorage'] !== null;   } catch(e){     return false;   } }
  • 41. Offline strategies for HTML5 web applications Web Storage: Pro Most compatible format up to now.
  • 42. Offline strategies for HTML5 web applications Web Storage: Con The data is not structured.
  • 43. Offline strategies for HTML5 web applications Web Storage: Con No transaction support!
  • 44. Offline strategies for HTML5 web applications Web SQL Database
  • 45. Offline strategies for HTML5 web applications Web SQL Database An offline SQL database based on SQLite, an general-purpose SQL engine.
  • 46. Offline strategies for HTML5 web applications Web SQL Database function prepareDatabase(ready, error) {   return openDatabase('documents', '1.0',      'Offline document storage', 5*1024*1024, function  (db) {     db.changeVersion('', '1.0', function (t) {       t.executeSql('CREATE TABLE docids (id, name)');     }, error);   }); } function showDocCount(db, span) {   db.readTransaction(function (t) {     t.executeSql('SELECT COUNT(*) AS c FROM docids', [],        function (t, r) {          span.textContent = r.rows[0].c;       }, function (t, e) {          // couldn't read database          span.textContent = '(unknown: ' + e.message +  ')';     });   }); }
  • 47. Offline strategies for HTML5 web applications Web SQL Database: Pro It`s a SQL database within the browser!
  • 48. Offline strategies for HTML5 web applications Web SQL Database: Con It`s a SQL database within the browser!
  • 49. Offline strategies for HTML5 web applications Web SQL Database: Con SQLite is slooooow!
  • 50. Offline strategies for HTML5 web applications Web SQL Database: Con The specification is no longer part of HTML5!
  • 51. Offline strategies for HTML5 web applications IndexedDB
  • 52. Offline strategies for HTML5 web applications IndexedDB A nice compromise between Web Storage and Web SQL Database giving you the best of both worlds.
  • 53. 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.
  • 54. Offline strategies for HTML5 web applications IndexedDB – Creating an ObjectStore indexedDB.open = function() {   var request = indexedDB.open("todos");   request.onsuccess = function(e) {     var v = "2.0 beta";     todoDB.indexedDB.db = e.target.result;     var db = todoDB.indexedDB.db;     if (v!= db.version) {       var setVrequest = db.setVersion(v);       setVrequest.onfailure = todoDB.indexedDB.onerror;       setVrequest.onsuccess = function(e) {         if (db.objectStoreNames.contains("todo")) {           db.deleteObjectStore("todo");         }         var store = db.createObjectStore("todo",  {keyPath: "timeStamp"});         todoDB.indexedDB.getAllTodoItems();       };     } else {       todoDB.indexedDB.getAllTodoItems();     }   };   request.onfailure = todoDB.indexedDB.onerror; };
  • 55. Offline strategies for HTML5 web applications IndexedDB – Adding data to ObjectStore indexedDB.addTodo = function() {   var db = todoDB.indexedDB.db;   var trans = db.transaction(['todo'],  IDBTransaction.READ_WRITE);   var store = trans.objectStore('todo');   var data = {     "text": todoText,     "timeStamp": new Date().getTime()   };   var request = store.put(data);   request.onsuccess = function(e) {     todoDB.indexedDB.getAllTodoItems();   };   request.onerror = function(e) {     console.log("Failed adding items due to: ", e);   }; };
  • 56. Offline strategies for HTML5 web applications IndexedDB – Retrieving data function show() {   var request = window.indexedDB.open("todos");   request.onsuccess = function(event) {     var db = todoDB.indexedDB.db;     var trans = db.transaction(["todo"],  IDBTransaction.READ_ONLY);     var request = trans.objectStore("todo").openCursor();     var ul = document.createElement("ul");     request.onsuccess = function(event) {       var cursor = request.result || event.result;       // If cursor is null, enumeration completed       if(!cursor) {         document.getElementById("todos").appendChild(ul);         return;       }       var li = document.createElement("li");       li.textContent = cursor.value.text;       ul.appendChild(li);       cursor.continue();     }   } }
  • 57. Offline strategies for HTML5 web applications IndexedDB – Deleting data indexedDB.deleteTodo = function(id, text) {   var db = todoDB.indexedDB.db;   var trans = db.transaction(["todo"],  IDBTransaction.READ_WRITE);   var store = trans.objectStore("todo");   var request = store.delete(id);   request.onsuccess = function(e) {     todoDB.indexedDB.getAllTodoItems();   };   request.onerror = function(e) {     console.log("Error Adding: ", e);   }; };
  • 58. Offline strategies for HTML5 web applications File API
  • 59. Offline strategies for HTML5 web applications File API FileReader API and FileWriter API
  • 60. Offline strategies for HTML5 web applications File API – Requesting access function onInitFs(fs) {   console.log('Opened file system: ' + fs.name); } function errorHandler(e) {   console.log('Error: ' + e.code); } window.requestFileSystem(window.TEMPORARY, 5*1024*1024  /*5MB*/, onInitFs, errorHandler);
  • 61. Offline strategies for HTML5 web applications File API – Requesting quota window.webkitStorageInfo.requestQuota(     PERSISTENT,      5*1024*1024 /*5MB*/,      function(grantedBytes) {       window.requestFileSystem(PERSISTENT, grantedBytes,           onInitFs, errorHandler);     },      function(e) {       console.log('Error', e); });
  • 62. Offline strategies for HTML5 web applications
  • 63. Offline strategies for HTML5 web applications File API – Creating a file function onInitFs(fs) {   fs.root.getFile('log.txt',    {create: true, exclusive: true},    function(fileEntry) {     // fileEntry.name == 'log.txt'     // fileEntry.fullPath == '/log.txt'   }, errorHandler); } window.requestFileSystem(window.TEMPORARY, 5*1024*1024  /*5MB*/, onInitFs, errorHandler);
  • 64. Offline strategies for HTML5 web applications File API – Reading a file function onInitFs(fs) {   fs.root.getFile('log.txt', {},    function(fileEntry) {     fileEntry.file(function(file) {        var reader = new FileReader();        reader.onloadend = function(e) {          var txtArea   =                document.createElement('textarea');          txtArea.value = this.result;          document.body.appendChild(txtArea);        };        reader.readAsText(file);     }, errorHandler);   }, errorHandler); } window.requestFileSystem(window.TEMPORARY, 5*1024*1024  /*5MB*/, onInitFs, errorHandler);
  • 65. Offline strategies for HTML5 web applications File API – Writing to a file function onInitFs(fs) {   fs.root.getFile('log.txt', {create: true},    function(fileEntry) {     fileEntry.createWriter(function(fileWriter) {       fileWriter.onwriteend = function(e) {         console.log('Write completed.');       };       fileWriter.onerror = function(e) {         console.log('Write failed: ' + e.toString());       };       var bb = new BlobBuilder();       bb.append('Lorem Ipsum');       fileWriter.write(bb.getBlob('text/plain'));     }, errorHandler);   }, errorHandler); } window.requestFileSystem(window.TEMPORARY, 5*1024*1024  /*5MB*/, onInitFs, errorHandler);
  • 66. Offline strategies for HTML5 web applications File API – Appending data to a file function onInitFs(fs) {   fs.root.getFile('log.txt', {create: false},    function(fileEntry) {     fileEntry.createWriter(function(fileWriter) {       fileWriter.seek(fileWriter.length);       var bb = new BlobBuilder();       bb.append('Hello World');       fileWriter.write(bb.getBlob('text/plain'));     }, errorHandler);   }, errorHandler); } window.requestFileSystem(window.TEMPORARY, 5*1024*1024  /*5MB*/, onInitFs, errorHandler);
  • 67. Offline strategies for HTML5 web applications File API – Deleting a file function onInitFs(fs) {   fs.root.getFile('log.txt', {create: false},    function(fileEntry) {     fileEntry.remove(function() {       console.log('File removed.');     }, errorHandler);    }, errorHandler); } window.requestFileSystem(window.TEMPORARY, 5*1024*1024  /*5MB*/, onInitFs, errorHandler);
  • 68. Offline strategies for HTML5 web applications File API – Creating directories function onInitFs(fs) {    fs.root.getDirectory('MyFolder', {create: true},     function(dirEntry) {     // do stuff...     }, errorHandler); } window.requestFileSystem(window.TEMPORARY, 5*1024*1024  /*5MB*/, onInitFs, errorHandler);
  • 70. Offline strategies for HTML5 web applications File API – Browser support? Up to now: Chrome only
  • 71. Offline strategies for HTML5 web applications File API – Browser support? But: idb.filesystem.js
  • 72. Offline strategies for HTML5 web applications Am I online?
  • 73. 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! }
  • 74. 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   } });