SlideShare ist ein Scribd-Unternehmen logo
1 von 77
Downloaden Sie, um offline zu lesen
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




         [...] 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

 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
   }
 });
Thank you!
http://joind.in/7073

Weitere ähnliche Inhalte

Was ist angesagt?

RDF Validation in a Linked Data World - A vision beyond structural and value ...
RDF Validation in a Linked Data World - A vision beyond structural and value ...RDF Validation in a Linked Data World - A vision beyond structural and value ...
RDF Validation in a Linked Data World - A vision beyond structural and value ...
Nandana Mihindukulasooriya
 
Apache Olingo - ApacheCon Denver 2014
Apache Olingo - ApacheCon Denver 2014Apache Olingo - ApacheCon Denver 2014
Apache Olingo - ApacheCon Denver 2014
Stephan Klevenz
 
Evolving Hadoop into an Operational Platform with Data Applications
Evolving Hadoop into an Operational Platform with Data ApplicationsEvolving Hadoop into an Operational Platform with Data Applications
Evolving Hadoop into an Operational Platform with Data Applications
DataWorks Summit
 
Interoperable Ajax Tools And Mashups Ferraiolo
Interoperable Ajax Tools And Mashups FerraioloInteroperable Ajax Tools And Mashups Ferraiolo
Interoperable Ajax Tools And Mashups Ferraiolo
rajivmordani
 
Stat 5.4 Pre Sales Demo Master
Stat 5.4 Pre Sales Demo MasterStat 5.4 Pre Sales Demo Master
Stat 5.4 Pre Sales Demo Master
reachtimsq
 

Was ist angesagt? (20)

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

Ähnlich wie Offline strategies for HTML5 web applications - pfCongres2012

SAS_Forum_2015_Data_Visualisation_With_HighCharts_D3
SAS_Forum_2015_Data_Visualisation_With_HighCharts_D3SAS_Forum_2015_Data_Visualisation_With_HighCharts_D3
SAS_Forum_2015_Data_Visualisation_With_HighCharts_D3
Vasilij Nevlev
 
WHAT IS HTML5? (at CSS Nite Osaka)
WHAT IS HTML5? (at CSS Nite Osaka)WHAT IS HTML5? (at CSS Nite Osaka)
WHAT IS HTML5? (at CSS Nite Osaka)
Shumpei Shiraishi
 

Ähnlich wie Offline strategies for HTML5 web applications - pfCongres2012 (20)

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

Mehr von 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...
Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...
Stephan Hochdörfer
 
Phing for power users - frOSCon8
Phing for power users - frOSCon8Phing for power users - frOSCon8
Phing for power users - frOSCon8
Stephan Hochdörfer
 
Real World Dependency Injection - oscon13
Real World Dependency Injection - oscon13Real World Dependency Injection - oscon13
Real World Dependency Injection - oscon13
Stephan Hochdörfer
 
Dependency Injection in PHP - dwx13
Dependency Injection in PHP - dwx13Dependency Injection in PHP - dwx13
Dependency Injection in PHP - dwx13
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
Offline Strategien für HTML5 Web Applikationen - dwx13
Stephan Hochdörfer
 
Your Business. Your Language. Your Code - dpc13
Your Business. Your Language. Your Code - dpc13Your Business. Your Language. Your Code - dpc13
Your Business. Your Language. Your Code - dpc13
Stephan Hochdörfer
 
Phing for power users - dpc_uncon13
Phing for power users - dpc_uncon13Phing for power users - dpc_uncon13
Phing for power users - dpc_uncon13
Stephan Hochdörfer
 
Offline-Strategien für HTML5 Web Applikationen - wmka
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örfer
 
Offline-Strategien für HTML5 Web Applikationen - bedcon13
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örfer
 
Real World Dependency Injection - phpugffm13
Real World Dependency Injection - phpugffm13Real World Dependency Injection - phpugffm13
Real World Dependency Injection - phpugffm13
Stephan Hochdörfer
 
Testing untestable code - ConFoo13
Testing untestable code - ConFoo13Testing untestable code - ConFoo13
Testing untestable code - ConFoo13
Stephan Hochdörfer
 
Offline-Strategien für HTML5Web Applikationen - WMMRN12
Offline-Strategien für HTML5Web Applikationen - WMMRN12Offline-Strategien für HTML5Web Applikationen - WMMRN12
Offline-Strategien für HTML5Web Applikationen - WMMRN12
Stephan Hochdörfer
 
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
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örfer
 
Wie Software-Generatoren die Welt verändern können - Herbstcampus12
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örfer
 
Testing untestable code - Herbstcampus12
Testing untestable code - Herbstcampus12Testing untestable code - Herbstcampus12
Testing untestable code - Herbstcampus12
Stephan Hochdörfer
 
Testing untestable code - oscon 2012
Testing untestable code - oscon 2012Testing untestable code - oscon 2012
Testing untestable code - oscon 2012
Stephan Hochdörfer
 
Introducing a Software Generator Framework - JAZOON12
Introducing a Software Generator Framework - JAZOON12Introducing a Software Generator Framework - JAZOON12
Introducing a Software Generator Framework - JAZOON12
Stephan Hochdörfer
 

Mehr von Stephan Hochdörfer (20)

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...
Offline. Na und? Strategien für offlinefähige Applikationen in HTML5 - Herbst...
 
Phing for power users - frOSCon8
Phing for power users - frOSCon8Phing for power users - frOSCon8
Phing for power users - frOSCon8
 
Real World Dependency Injection - oscon13
Real World Dependency Injection - oscon13Real World Dependency Injection - oscon13
Real World Dependency Injection - oscon13
 
Dependency Injection in PHP - dwx13
Dependency Injection in PHP - dwx13Dependency Injection in PHP - dwx13
Dependency Injection in PHP - dwx13
 
Offline Strategien für HTML5 Web Applikationen - dwx13
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
Your Business. Your Language. Your Code - dpc13Your Business. Your Language. Your Code - dpc13
Your Business. Your Language. Your Code - dpc13
 
Phing for power users - dpc_uncon13
Phing for power users - dpc_uncon13Phing for power users - dpc_uncon13
Phing for power users - dpc_uncon13
 
Offline-Strategien für HTML5 Web Applikationen - wmka
Offline-Strategien für HTML5 Web Applikationen - wmkaOffline-Strategien für HTML5 Web Applikationen - wmka
Offline-Strategien für HTML5 Web Applikationen - wmka
 
Offline-Strategien für HTML5 Web Applikationen - bedcon13
Offline-Strategien für HTML5 Web Applikationen - bedcon13Offline-Strategien für HTML5 Web Applikationen - bedcon13
Offline-Strategien für HTML5 Web Applikationen - bedcon13
 
Real World Dependency Injection - phpugffm13
Real World Dependency Injection - phpugffm13Real World Dependency Injection - phpugffm13
Real World Dependency Injection - phpugffm13
 
Testing untestable code - ConFoo13
Testing untestable code - ConFoo13Testing untestable code - ConFoo13
Testing untestable code - ConFoo13
 
A Phing fairy tale - ConFoo13
A Phing fairy tale - ConFoo13A Phing fairy tale - ConFoo13
A Phing fairy tale - ConFoo13
 
Offline-Strategien für HTML5Web Applikationen - WMMRN12
Offline-Strategien für HTML5Web Applikationen - WMMRN12Offline-Strategien für HTML5Web Applikationen - WMMRN12
Offline-Strategien für HTML5Web Applikationen - WMMRN12
 
Testing untestable code - IPC12
Testing untestable code - IPC12Testing untestable code - IPC12
Testing untestable code - IPC12
 
Große Systeme, lose Kopplung, Spaß bei der Arbeit! - WDC12
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
 
Wie Software-Generatoren die Welt verändern können - Herbstcampus12
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
 
Testing untestable code - Herbstcampus12
Testing untestable code - Herbstcampus12Testing untestable code - Herbstcampus12
Testing untestable code - Herbstcampus12
 
Testing untestable code - oscon 2012
Testing untestable code - oscon 2012Testing untestable code - oscon 2012
Testing untestable code - oscon 2012
 
Introducing a Software Generator Framework - JAZOON12
Introducing a Software Generator Framework - JAZOON12Introducing a Software Generator Framework - JAZOON12
Introducing a Software Generator Framework - JAZOON12
 
The state of DI - DPC12
The state of DI - DPC12The state of DI - DPC12
The state of DI - DPC12
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

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
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 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);
  • 69.
  • 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   } });
  • 75.