开发者

HTML5 - localStorage, Cookies, and SQL

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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜