2

Based on a lot of search results I've seen on SO, HTML5's localStorage feature appears to be beneficial over Cookies only when you're concerned with storing large portions of data that don't need to be transmitted to the server. ( Local Storage vs Cookies )

I'm having difficulty wrapping my head around how/why someone would use this feature. Can anyone provide a link to a real-world example that shows how localStorage is beneficial?

Also, is there ever a case where localStorage would be used over...say...writing certain information to the SQL db?

Sorry if this is a duplicate of the myriad HTML5 questions on this site. I've read through a few and none of them answered my questions completely. Thanks in advance!

Community
  • 1
  • 1
octopusbones
  • 89
  • 1
  • 8
  • 1
    I would always use localStorage if the data isn't needed by the server. It avoids bloating your HTTP requests, which is especially important if you're doing a lot of AJAX (or loading a lot of static content from the same domain, but that's a bad idea anyway). I like to use localStorage for caching data client-side. – Michael Mior Aug 25 '11 at 15:21
  • So I get that...but maybe I'm just not seeing the big picture. It's not that I disagree that it's a valuable feature...I just haven't connected the dots in a real-world situation yet maybe. So, essentially, it's an alternative to storing certain information in a hidden field or tucking it away in some other piece of HTML for future reference. Does that sound about right? – octopusbones Aug 25 '11 at 15:33
  • 1
    Sure :) For example, Twitter uses it to cache displays of tweets. – Michael Mior Aug 25 '11 at 15:43

1 Answers1

6

localStorage is a great place to store application settings that you'd like to persist between sessions (as opposed to sessionStorage) and not be transmitted to the server (as opposed to a cookie). Previously, to avoid having cookie based settings transmitted to the server needlessly, you'd have to use a different subdomain just for cookies.

The next important advantage is that although under the hood localStorage uses SQLite, all localStorage values are cached in memory by the browser. So while with the database API each executeSql statement is async and would require a callback function to grab the data, localStorage is completely synchronous as it fetches data straight from a memory cache. This means that storing and retrieving large chunks of data from localStorage is extremely fast.

The way the localStorage object has been implemented also makes really easy and intuitive to use in your code. Did you know for example, that instead of using getItem and setItem you can use localStorage like any other object?

localStorage.someKeyName = 'someValue';
alert(localStorage.someKeyName); // alerts 'someValue'
delete localStorage.someKeyName; // removes the key

Compare this to the amount of code required to retrieve a single record from the database:

var db = openDatabase('myDb', '', '', 1024);
db.compatibleReadTransaction(function (t) {
    t.executeSql('SELECT someField FROM someTable WHERE somePrimaryKey = 1', function(t, r) {
        console.log(r.rows.item(0));
    }, function () {
        // error
    });
});

Real-world example

The Guardian web app at g.joeblade.com stores all article content in localStorage. This means that page loading is instaneous. If the content were to be stored in the database, it wouldn't be nearly as fast as each article would have to be fetched asynchronously from the database, and then there's the overhead of invoking the SQLite query engine, running the callback, and so on.

Matthew
  • 15,464
  • 2
  • 37
  • 31
  • So the article content is stored in a SQL db, served to the user, cached locally in their localStorage db and then referenced from there anytime in the future. Does that sound about right? Does it mean there's always a javascript check on page-load to test if the browser has already cached the data potentially being served? – octopusbones Aug 25 '11 at 15:56
  • Yes and yes. The scenario might look something like this: the app just stores a date in localStorage that records the last time it was updated. When the app starts, this is is sent to the server, which returns any new content since that date, which in turn is added to the rest of the content in localStorage, and the oldest content is removed to save space. – Matthew Aug 25 '11 at 16:02
  • Also, is there some sort of ORM-style querying feature built into the localStorage api? For instance, rather than writing a SQL statement, I would reference items in the db as objects? e.g. someTable.someField.Where(somePrimaryKey = 1) ? – octopusbones Aug 25 '11 at 16:02
  • 1
    No. localStorage is exactly like any other JavaScript object, except that the values of its properties can only be strings. – Matthew Aug 25 '11 at 16:03
  • BTW If you wanted to store an array of articles say, you would JSON-encode it, store the resulting string in localStorage, then JSON-decode that value when your app starts up. – Matthew Aug 25 '11 at 16:15
  • oh snap! that's a great idea. i guess i'm jumping on the localStorage bandwagon. it sounds great! – octopusbones Aug 25 '11 at 16:30