Offline. Na und?

Stephan Hochdörfer // 17.03.2015

Über mich

  • Stephan Hochdörfer
  • Head of Technology, bitExpert AG
    Mannheim
  • S.Hochdoerfer@bitExpert.de
  • @shochdoerfer

  • #DevOps, #Automation, #unKonf

Das mobile Zeitalter

Offline First!




« We live in a disconnected & battery powered world, but our technology and best practices are a leftover from the always connected & steadily powered past. »
- offlinefirst.org

Ist HTML5 noch nicht bereit?

HTML5 kann mehr!

Was bedeutet "offline"?




« Offline storage is about capturing specific data generated by the user, or resources the user has expressed interest in. » - Eric Bidelman

Offline Container




  • Hybrid Container
  • App Cache
  • Service Workers

Hybrid Container

App Cache




« The cache manifest in HTML5 is a software storage feature which provides the ability to access a web application even without a network connection. »
- Wikipedia

App Cache: Einrichtung

<!DOCTYPE html>
<html lang="en" manifest="cache.manifest">
CACHE MANIFEST
#2015-03-17

js/app.js
css/app.css
favicon.ico
http://someotherdomain.com/image.png

App Cache: Konfiguration

CACHE MANIFEST
# 2015-03-17

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

App Cache: Javascript

// Check if a new cache version is available
window.addEventListener('load', function(e) {
  
  window.applicationCache.addEventListener('updateready', 
      function(e) {
    
      if(window.applicationCache.status == 
          window.applicationCache.UPDATEREADY) {
      
          window.applicationCache.swapCache();
      
          if (confirm('Update laden?')) {
	      window.location.reload();
          }
      }

  }, false);

}, false);

App Cache: Fallstricke


  • Dateien werden immer
    aus dem Cache ausgeliefert!
  • Nur Änderungen an der
    Manifest Datei lösen ein Update
    aus
  • Nicht gecachte Ressourcen
    erscheinen nicht auf gecachten
    Seiten
  • Nie die Manifest Datei cachen!

Service Worker




« [...] between the network and a document renderer,
allowing the service worker to provide content
for documents, even while offline. » - W3C

Wie Daten speichern?



  • Web Storage
  • Web SQL Database
  • IndexedDB
  • File API

Web Storage





Key/Value Datenspeicher.
Sehr einfach benutzbar.

Web Storage: Beispiel

var myObject = {
  key1: "value 1",
  key2: 500,
  key3: false
};
// store item

localStorage.setItem(
  "key", 
  JSON.stringify(myObject)
);
// retrieve item

myObject = JSON.parse(
    localStorage.getItem("key")
); 

Vorteile & Nachteile


  • Vorteil: Verfügbar in aktuellen
    Browsern - Ja, auch im IE8!
  • Vorteil: Kein HTTP overhead
  • Nachteil: Speichert nur Strings
  • Nachteil: Schlechtes Quota
    Handling
  • Nachteil: http:// vs. https://

Web SQL Database





Eine lokale SQL Datenbank auf
SQLite Basis eingebettet im Browser.

Web SQL: Beispiel

var db = openDatabase('mydb', '1.0', 'DB',  5 * 1024 * 1024 );

db.transaction(function (tx) {
    tx.executeSql(
	'SELECT * FROM table',
	[],
	function(tx, results) {
	    var len = results.rows.length;
	    for(var i = 0; i < len; i++) {
		    // render item
	    }
	},
	function(tx, ex) {
	    alert("Error: " + ex.message);
	}
    );
});

Vorteile & Nachteile


  • Vorteil: Versionierbarkeit des
    Schemas
  • Vorteil: Eine Datenbank im
    Browser!
  • Nachteil: Eine Datenbank im
    Browser!
  • Nachteil: Nicht mehr Teil der
    HTML5 Spezifikation!

IndexedDB




Kompromiss aus Web Storage
und Web SQL Database.

IndexedDB: Initialisierung

var db = null;
var request = indexedDB.open("mydb");
request.onfailure = onError;
request.onsuccess = function(e) {
  db = request.result;
  var v = "1.0";
  if(v != db.version) {
    var verRequest = db.setVersion(v);
    verRequest.onfailure = onError;
    verRequest.onsuccess = function(e) {
      var store = db.createObjectStore("table",
	{
	  keyPath: "id",
	  autoIncrement: true
	});

      e.target.transaction.oncomplete =  function() {};
    };
  }
};

IndexedDB: Daten speichern

try {
    var trans   = db.transaction(["mydb"], 
	IDBTransaction.READ_WRITE);

    var store   = trans.objectStore("table");
    var request = store.put({
      "MyKey1": 123,
      "MyKey2": "some random text"
    });
}
catch(ex) {
    // @TODO: Exception handling ;)
}

IndexedDB: Daten löschen

try {
    var trans   = db.transaction(["mydb"], 
	IDBTransaction.READ_WRITE);

    var store   = trans.objectStore("table");
    var id      = 1;
    var request = store.delete(id);
}
catch(ex) {
    // @TODO: Exception handling ;)
}

IndexedDB: Daten lesen

try {
    var trans = db.transaction(["mydb"], IDBTransaction.READ);
    var store = trans.objectStore("table");

    var keyRange = IDBKeyRange.lowerBound(0);

    var cursorRequest = store.openCursor(keyRange);
    cursorRequest.onsuccess = function(e) {
      var result = e.target.result;
      if(!!result == false) {
	return;
      }

      // @TODO: process result.value

      result.continue();
    };
}
catch(ex) {
    // @TODO: Exception handling ;)
}

Vorteile & Nachteile


  • Vorteil: Versionierbarkeit des
    Schemas
  • Vorteil: Der "neue Standard"
  • Nachteil: NoSQL Denke kann
    gewöhnunsbedürftig sein
  • Nachteil: Probleme unter
    iOS / Safari 8.x

File API




« [...] provides an API for representing file objects in web applications and programmatic selection and accessing their data. » - Wikipedia

Browserunterstützung?

Web Storage Web SQL DB IndexedDB File API
IE 8.0 10.0 10.0 10.0
Firefox 11.0 11.0 11.0 19.0
Chrome 18.0 18.0 18.0 18
Safari 5.1 5.1 (8.0) 7.1
iOS 3.2 3.2 (8.1) 7.1
Android 2.1 2.1 4.4 4.4

Speicherplatz?

Web Storage Web SQL DB IndexedDB File API
IE 10 MB 500 MB 500 MB
Firefox 10 MB 50 MB 50 MB
Chrome 5 MB
Safari 5 MB 5 MB 5 MB
iOS 5 MB 5 MB 5 MB
Android 5 MB ? ?







Vielen Dank! Fragen?