Javascript

LocalStorage Made Easy with store.js

Written by Kevin Liew on 21 Apr 2014
23,795 Views • Shares
1 comment

A few years back, whenever we think of storing simple data on client side, we think of cookies. It wasn't the only solutions, Microsoft invented userData and Adobe introduced "Flash Cookies", but both of them failed intermittently.

Cookies aren't the best solution. It only can store about 4KB of data, it's not encrypted with HTTP request and it's included in every HTTP request which could slow down your web application.

Thankfully, in HTML5 specification, there's a new feature called - HTML5 Storage a.k.a. Web Storage.

Quoting from Wikipedia:

Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity (5 MB per origin in Google Chrome, Mozilla Firefox, and Opera; 10 MB per storage area in Internet Explorer) and better programmatic interfaces.

Despite of the different browser storage capacities, you have to know localStorage isn't supported by IE7 and below too. And it's not acceptable as there are still corporates still using legacy IE browsers.

The good news is, Microsoft implemented something similar called userData which allows web pages to store up to 64 KB of data per domain. Therefore, it's possible to detect localStorage and if there isn't, fallback to userData for IE7 and below. That should covers most browsers!

Introducing store.js - a localStorage wrapper for all browsers without using cookies or flash. It uses localStorage, globalStorage and userData under the hood. store.js use localStorage when available, and falls back on the userData in IE6 and IE7. No flash to slow down your page load. No cookies to fatten your network requests.

Here is its API:

// Store 'marcus' at 'username'
store.set('username', 'marcus')

// Get 'username'
store.get('username')

// Remove 'username'
store.remove('username')

// Clear all keys
store.clear()

// Store an object literal - store.js uses JSON.stringify under the hood
store.set('user', { name: 'marcus', likes: 'javascript' })

// Get the stored object - store.js uses JSON.parse under the hood
var user = store.get('user')
alert(user.name + ' likes ' + user.likes)

// Get all stored values
store.getAll().user.name == 'marcus'

// Loop over all stored values
store.forEach(function(key, val) {
    console.log(key, '==', val)
})	

With store.js, you will not have to worry about browser supports.

SPECIFICATIONS & DOWNLOAD

Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

1 comment
Saleem 1 year ago
Awesome tutorial. Great explanation on store.js about its use of local, global and userData as storage and ie6/7's fallback strategies.
Reply