CLIENT-SIDE STORAGE APIs

Supporting Offline Web Apps...
...and Beyond

Germán Toro del Valle (gtv@tid.es, @gtorodelvalle)

WHY SHOULD I CARE

  1. Do not take connectivity for granted (offline operation)
  2. Performance (avoid unneeded data download)

THE OPTIONS

  1. Web Storage API
  2. Web SQL Database API
  3. Indexed Database API
  4. File API

COMMONALITIES

  • Data is stored in the client's hard drive
  • Data is tied to an origin (protocol + domain [+ subdomain] + port)
  • Limited storage size:
    • Browser-specific
    • Currently per origin and API
    • Increasable under user acceptance

Web Storage API

  • Key / value pairs
  • Objects provided:
    • localStorage
    • sessionStorage
if (localStorage) {
    // Storage.
    localStorage.key = value;
    // Retrieval.
    console.log(localStorage.key);
}
  • NOTE: Values are stored as Strings (although the spec says otherwise)

Web SQL Database API

  • Structured database (with all the functionalities and complexities of SQL databases)
  • Transaction-oriented
db = openDatabase('myDB', '1.0', 'My first Web SQL DB', 8192);
db.transaction(function (tx) {
  tx.executeSql("CREATE TABLE IF NOT EXISTS..." // SQL statement.
    [], // Parameter array.
    function onTXSuccess(transaction, results) { ... },
    function onTXError(transaction, error) { ... }
  );
});
  • NOTE: Deprecated (it won't be supported by Firefox or IE)

Indexed Database API

  • Result of previous experience with the Web Storage API and Web SQL Storage API:
    • Storing and retrieving objects indexed by key (key / value pairs)
    • Transaction-oriented (auto-commit)
    • Asynchronous and synchronous (Web Workers) API
var request = window.indexedDB.open("MyFirstIndexedDB", 5);
request.onerror = function(event) {
  // Do something with request.errorCode!
};
request.onsuccess = function(event) {
  // Do something with request.result!
};

File API

  • Focus on:
    • Large files
    • Binary content
  • Asynchronous and synchronous (Web Workers) API
window.requestFileSystem(/* type */ window.TEMPORARY, /* size */ 8192,
    /* success */ initFS, /* error */ errorHandler);
function initFS(fs){
    fs.root.getDirectory('Docs', {create: true}, function(dirEntry) {
        console.log(dirEntry.name + 'directory available');
    }, errorHandler);
}
function errorHandler(){
    console.log('An error occured');
}
  • NOTE: Very early specification (currently under discussion) (partial implementations + proprietary extensions)

CONCLUSIONS

// In the following line, you should include the prefixes of
// the implementations you want to support.
window.indexedDB = window.indexedDB || window.mozIndexedDB ||
    window.webkitIndexedDB || window.msIndexedDB;

Thanks! ;-)