Enhancing Client-Side Storage with HTML5
Today’s guest post is from Christopher Haupt of Webvanta, an Engine Yard partner. Christopher is co-founder of Webvanta, co-host of the Learning Rails podcast, and frequent contributor at Ruby, Web Development and Design conferences, meet-ups, and publications.
Webvanta is co-sponsoring the North Bay Web Design Conference on April 12, 2011 in Rohnert Park, CA. Check out the speaker lineup and to register to attend by visiting the North Bay Web Design Conference event site.
Our team finds that we get the greatest leverage out of our existing collection of code snippets by organizing them into well structured, easy to maintain libraries of pluggable modules. In the previous article of this two part series, we focused on how to reuse our large collection of JavaScript snippets by making them into jQuery plugins. In this second article we briefly examine the Web Storage technology that has come out of the HTML5 specification process. We then show how simple it is to wrap it within a jQuery plugin.
As your interactive front-end code becomes more sophisticated, it is common to have data supplied from the back-end that is relatively expensive to deliver either because of its size or cost to generate. Until now, the options for holding onto such data locally have been limited. You could store small pieces of data in cookies, leverage optional third-party browser plugins, or use browser specific extensions.
If you hoped to have a cross-browser, standards-based solution that gave you the fewest headaches, your hopes were dashed, especially if you needed to deal with desktop AND mobile browsers.
Now there is a bit of hope. A set of client-side data technologies originally part of the HTML5 specification (now spun off) have been implemented in many recent browser engines. We’re going to look briefly at Web Storage as the most stable of the work to date. Two other candidates exist: Web Database and Indexed Database, but they have bogged down in specification politics among the browser builders, so caveat emptor.
###Web Storage API
Web Storage introduces two key/value storage containers: localStorage and sessionStorage. Both store data that are tied to a specific domain. The former persists data across browser sessions while the latter erases it when the browser session ends.
This also means that data stored in localStorage is accessible between multiple windows open at the same time, while sessionStorage is confined to an individual window.
Both are implemented today in Chrome (5+), FireFox (3.5+), Safari (4+), Internet Explorer (8+), Opera (10.5+), as well as IOS and Android devices. Per the current draft specification, a mostly arbitrary size limit of 5MB exists for the amount of data that can be stored per domain. When this quota is reached, browsers may optionally prompt the user for permission to increase the limit.
The API is very simple. You access either storage system in JavaScript by making calls on its object that hangs off of the global window context: window.localStorage or window.sessionStorage.
The setItem(key, value) method is used to store data. The key is always a string. Retrieval is just as easy: getItem(key).
You can retrieve the number of keys currently stored within the container with the “length” attribute. It is possible to enumerate the keys by numeric index position with key(index).
Items can be removed from storage with the removeItem(key) method. You can atomically cause the entire storage system to be emptied using the clear() method. ###Dealing With Older Browsers While it is exciting that Web Storage is implemented so broadly, it seems likely that you will still have to deal with older browsers who lack this functionality. You have several options:
- Continue to use server-side storage and deliver data as needed. This is probably a fall-back to existing functionality you have today, using Ajax and various JavaScript functions to negotiate for the data needed at any given moment. If your data is larger than cookie limits of 4KB, you have to do this in either case.
- If your data needs are smaller, you might be using cookies already. There are many scripts and plugins out there that you can easily use.
- If you are developing for a specific browser or platform, browser specific functions or 3rd party plugins such as Adobe Flash may be suitable.
If you decide to use Web Storage, you can easily check for its existence by looking for it attached to the global “window” object:
if (typeof window.localStorage!=='undefined') {
}
Checking for sessionStorage is similar.
###Plugging in to Web Storage Let’s create a simple jQuery Utility Plugin for using localStorage and bring together what we’ve learned to date. We might want to use this plugin to implement a larger basic caching strategy for larger client data and accelerate some of our front-end UI.
(function($){
$.webvantaStorage = {
Local: {
set: function(k,v){localStorage.setItem(k,v)},
get: function(k) {return localStorage.getItem(k)},
remove: function(k) {localStorage.removeItem(k)},
clear: function(k) {localStorage.clear()}
}
}
})(jQuery);
In this example, we’ve created a minimal “webvantaStorage” namespace and placed our “Local” object literal within it. Local itself implements a really basic version of the Web Storage API.
Once defined, we can use this easily enough:
$.webvantaStorage.Local.set("name", "Chris");
and
var myname = $.webvantaStorage.Local.get("name");
This is all pretty simplistic. What would be more interesting is if we were to check to see if Web Storage is available, and if not, fallback, perhaps to cookies. ###Not Re-inventing the Wheel As it turns out, there are existing jQuery plugins that do just that. One simple and very tiny option is the jQuery Storage plugin by Dave Schindler. Currently, it only handles localStorage and implements fallback to cookies, but it would be trivial to extend it to support sessionStorage.
Another interesting plugin is Andris Reinman’s jStorage which implements alternate storage strategies for older browsers beyond just cookie use.
Even more alternatives will pop-up if you do a search, and before long you’ll notice that the plugin community is alive and very active within the jQuery world. ###Putting It All Together It doesn’t matter whether you need to wrap an external set of functionality to provide an in-house API, or you just want to clean up a set of wildly different JavaScript utilities that developed over a period of several years. jQuery provides a clean, relatively simple to use framework for modularizing your JavaScript code. Indeed, it has helped us to develop a nice toolbox that saves valuable time when tackling new features or projects.
About Webvanta
Webvanta provides a hosted CMS and site-building services for designers and front-end developers. Their platform is built on Ruby on Rails and is hosted by Engine Yard. Webvanta offers a free ebook, 5 Tips for Building Better Sites, that summarizes the key lessons learned from being involved with 200+ sites in the past two years.
Webvanta is co-sponsoring the North Bay Web Design Conference on April 12, 2011 in Rohnert Park, CA. Check out the speaker lineup and to register to attend by visiting the North Bay Web Design Conference event site.
Share your thoughts with @engineyard on Twitter