Channels ▼
RSS

Web Development

The localStorage API


Example: Facebook Mobile

The mobile-friendly version of the Facebook website lets users find friends when posting status updates or searching for profiles, and gives users a fast autocomplete experience by caching the friends information in localStorage. Users don't add new friends that often, so Facebook can be OK with the data being a little bit stale and refreshing it when it has the chance. The Twitter web client does something similar, to give a fast autocomplete when mentioning usernames in a status update.

Facebook stores all the autocomplete data in a single "typeahead" key:

typeahead {"time": 1329151694363, "value": {"friends": [{"path": "/anton.kovalyov", "photo": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/186412_506803098_992151709_q.jpg", "text": "Anton Kovalyov", "uid": 506803098,},…

Example: Google Mobile

Both Google Mobile and Bing Mobile use localStorage to cache their HTML, CSS, and JS, to reduce the download size of their search pages. To accomplish this, they assign IDs to the various parts of their Web page, store the Web page parts in localStorage, and remember IDs and expirations in a cookie. When their server sees that cookie, it decides not to resend the stored parts. If for some reason the cookie is there but the data isn't, then the cookie is cleared, the page is reloaded, and the server sends the whole page.

Google and Bing are two of the most popular websites in the world, so it makes sense for them to optimize their website delivery; but this is definitely an advanced technique, and this level of optimization is probably not needed by most sites.

Here's an example of what Google stores in localStorage, and a snippet of their JS code for checking it:

mres.-8Y5Dw_nSfQztyYx <style>a{color: #11c} a:visited{color: #551a8b} body{margin:0;pad…
mres.-Kx7q38gfNkQMtpx

<script> //<![CDATA[ var Zn={},bo=function(a,b){b&&Zn[b]||(ne…
mres:time.-8Y5Dw_nSfQztyYx 1301368541872
mres:time.-Kx7q38gfNkQMtpx 1301368542755
var c=localStorage.getItem("mres."+a);
if (c) {
    document.write(c);
    localStorage.setItem("mres:time."+a,Date.now());
} else {
     window._clearCookie("MRES");
     document.location.reload(!0);
}

Example: ESRI MAPs

Despite the fact that localStorage can only store strings, it can be used to cache images by converting them from binary data into data URIs. If your Web app uses a large number of images, you may want to do this. For example, the ESRI Maps API includes an option for caching map tile images in localStorage, by using a key for each tile URL.

http://server…/tile/12/1409/2075 /9j/4AAQSkZJRgABAQEAYABgAAD/2wB…
http://server…/tile/12/1410/2077 /9j/4AAQSkZJRgABAQEAYABgAAD/2wB…

Making Your App Work Offline

Using the same techniques for improving website performance, localStorage can be used for enabling a website to work offline.  However, since websites can be used offline for indefinite amounts of time (like when a user is on vacation on a desert island), you need to think carefully about what you cache and for how long. It's fine to have stale data for a few minutes on the Web, but what about for a few hours or a whole day on a mobile device? In addition, if you want a website to work offline, you have to cache all of the necessary data, not just the data that make the app perform better.

(Note: HTML5 also offers the cache manifest API for storing resources offline, so you should try to use that in addition to localStorage when designing an offline website.)

Example: EatDifferent

The mobile app for EatDifferent is actually written in HTML5, thanks to using PhoneGap as a wrapper API to access native APIs and present it as a native app. That means that I can use localStorage to help it continue working when it's offline. The app remembers the profile information for the last logged in user, as well as previously fetched logs. Once it successfully connects to the Internet, it tries to re-fetch both the user profile and log data, and refreshes the UI when there's new data.

It stores the user profile in one key, and stores each log in a key based on the user profile and log date:

lscache-user {"first_name":"Testy", "last_name":"McTesterFace", "id", 166, …
lscache-166:log02/14/2012

{"measurements":{"weight":{"units":"","value":"150"}, "meals":[{"what":"sausage","when":"12:00pm",…

Best Practices

Now that you've seen everything that you can do with client-side storage, and localStorage in particular, here are some best practices to keep in mind:

  • Pick good key names: Your localStorage key names are like global variables across your entire domain — and as we know, it's easy for global variables to clash with each other, particularly when a site grows in size or number of developers. You can use pseudo namespaces, however, by prefixing the key name with the section of the site it's used in. As a general rule, it never hurts to go with a longer, more descriptive key names.
  • Guard private data: You should be careful about storing sensitive information like credit-card details. It's still possible for hackers to use DNS spoofing to access the localStorage of a website, and we may find out in the future that there are other ways hackers can access localStorage (it took a few years to discover all the cookie exploits, after all).
  • Be quota aware: Whenever you use any client-side storage option, you should be aware that quotas exist. Use libraries that handle the over-quota exception, and code in a way that doesn't assume stored data will be stored forever.
  • Use a library: You can use the raw localStorage API, but the available abstraction libraries make your use of localStorage more robust — and they can make it easier to switch to more appropriate client-side storage once there are viable options.

Conclusion

Web developers have made do with cookies and hacks for a long time, but we're now at a time where we can start seriously considering other options for client-side storage. We have localStorage in all the modern browsers, and it looks like we are close to having IndexedDB and the File API in them soon. You can start using localStorage now to improve your websites using many third-party libraries. We can look forward to a future in which we can pick the absolute best tool for the job.


Pamela Fox spent five years at Google helping developers use the Maps and Wave APIs in their apps, and is now working on her own Web apps using a mix of Python, JavaScript, and HTML5.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 
Dr. Dobb's TV