I recently tried to store locally the content of a form to make it resilient to inadvertent tab closing and crashes. Here is what I learned about the different ways to achieve client-side storage.
Cookies can crumble
Cookies are not a valid storage mean, as their size is limited to roughly 4000 characters (4KB) and act as a ball and chain, slowing down the responsiveness of websites. localStorage on the other hand, has been designed for that exact purpose, but is not available in IE6, IE7 and Firefox3.
store.js to the rescue
The first task was thus to search for a fallback solution (or shim or polyfill) available in those older browsers. It turns out that store.js, by Marcus Westin (@marcuswestin), wraps localStorage and fallbacks together in a concise API, with a light file-size (2KB once minified and gzipped along with json2.js). Here is a short usage example:
How does it work?
On Firefox2 and Firefox 3, it uses the globalStorage API, and on IE6 and IE7 it falls back to userData behavior, which has two important limitations you should be aware of:
- storage is limited to 128KB (vs. 5-10MB for localStorage), that’s still a lot of text,
- storage is subject to a same folder policy, meaning that pages in different folders should not be able to access the same stored items.
The second limitation can be really annoying, but it is possible to work around it by loading the code in an iframe. This trick will likely be integrated into Marcus’ own code.
Crash proof forms
With this script, I was able to build Persival, a simple jQuery plugin that can watch a form for changes and persist the values immediately:
A more complex demonstration page features the form people face when they want to report a bug affecting Firefox (you’ll see that it’s actually not as hard as it seems). If you start to fill the form, then close the tab and click on the same link again you should see the magic happening. A simple but welcome improvement to the user experience, isn’t it?
Chris Heilmann also demonstrated how client-side storage can be used to cache Web services data and maintain the state of a User Interface: localStorage and how to use it.
Persival is young but already yours, feel free to use it, learn from it and improve it.
Maybe there is a similar topic you would like to see covered in a next blog post? Let us know!
Developer Relations Team, long time jQuery contributor and Open Web enthusiast. @louis_remi