Skip to Content

Among the myriad of axioms, HTML5 has a very specific mantra – Mobile/Offline first. Building mobile/offline first web-apps have always been irksome, given the stripped down memory and processing strengths of mobile devices and the end user’s craving for luxury or ease of use. Surprisingly, HTML5 takes care of most of these legitimate demands. There are a couple of APIs which are noteworthy in this regard:

  1. WebStorage
  2. IndexedDb
  3. FileSystem

    

This article will focus on WebStorage API (Client-Side Storage).

History

It isn’t the case that web developers are oblivious to the concept of client-side storage. HTTP Session-Cookies have always been the loyal servant. They have been primarily used to store server side information on the client. However, if I could jot down the shortcomings of cookies:

  1. Smaller in size ~ 4KB – doesn’t allow to store bigger data
  1. Unsafe/vulnerable – major problems like cookie data leaking across windows or cookie theft etc. are setbacks.
  1. Sent with every HTTP request made to the server

    

Turn the tables

Enter WebStorage. It’s a specification which could be (arguably) concluded as the successor of cookies. It provides persistent storage as well as storage with expiration time. It has a larger size limit (upto ~5MB). It is a key-value store. Typical use cases could include storing friends list or an online music player playlist etc. on the client which doesn’t demand frequent updates or server round-trips.

WebStorage specification has 2 major APIs, each of which provide access to a list of key/value pairs. Though the access APIs are fairly simple, they are synchronous. Keys in these lists are strings.

  1. localStorage – this is a client storage API which lets you store data persistently without any expiration date. So basically it spans multiple sessions. Data is not lost upon the end of a session (or closing of a tab or window).

Usage:

if(window.localStorage){ //check for support

localStorage.setItem(key, value); //set a key/value pair in the list

    var item = localStorage.getItem(key); //get the value for a particular key

    localStorage.removeItem(key); // delete a key from the list

    localStorage.clear(); // clear the entire list

}

The setItem method must check if a key/value pair with the given key exists or not. Further, if does, then the corresponding value is updated with the new value provided. However, in case of an exception wherein the value for the key could not be set, then the method throws a QuotaExceededError exception. It’s a better practice placing them in try/catch blocks:

try {

localStorage.setItem(key, value);

}

catch(e) {

if(e.name === ‘QUOTA_EXCEEDED_ERR’) {

//quota exceeded

}

}

           2. sessionStorage – this API is almost identical to the localStorage except that the data stored have a expiration time. The data                    stored in the sessionStorage object are active only in the current session.

    

Usage:

if(window.sessionStorage){ //check for support

sessionStorage.setItem(key, value); //set a key/value pair in the list

    var item = sessionStorage.getItem(key); //get the value for a particular key

    sessionStorage.removeItem(key); // delete a key from the list

    sessionStorage.clear(); // clear the entire list

}

Web Storage Events

Whenever data is set/retrieved from the web storage object, a storage event is fired on the window object which we can be listen to.

window.addEventListener(‘storage’, function(evt){

//do whatever is necessary

}, false);

Support

Browser support could be found here: link

Gotchas

The simplicity of the API comes at a price. The price is paid when complex or substantially large data is stored in the WebStorage objects:

  1. There exists no clean way of detecting when we reach the 5MB storage limit in which case the QuotaExceededError exception is thrown. Note that an exception could also be thrown if the user has disabled storage on the device. On my machine running Windows 7, Chromium 35, I was able to store 5200000 characters successfully (use this link for carrying out the test).
  2. It lacks indexing. Hence it’s an O(n) linear search for retrieving data.
  3. It is synchronous i.e. it’s blocking on the main application thread. It actually performs file I/O on the machine and disk IO is particularly problematic because it’s non-deterministic for a multitude of reasons. A simple disk operation can take anywhere from zero milliseconds to a few seconds depending on how occupied the machine is.
  4. Manual serialization/de-serialization of data to/from strings need to be done while storing/retrieving data. This also causes further drop in performance.
  5. localStorage data is isolated based on the domain, port and scheme as well. It does make sense that data should be isolated based on domain, however isolating data based on the scheme i.e. http and https makes it quite tough to synchronize.
  6. Data is always loaded by browser onto the localStorage whether we visit a particular website again or not. This causes severe performance drops as browsers sometimes end up turning unresponsive.
  7. It has been found that sessionStorage data whose sole purpose is to be stored for the current session only, happen to restore or survive browser crashes. The Restore Session option somehow assorts data pertaining to the sessionStorage object as well.

Conclusion

In my opinion, Web Storage fares well while storing insensitive data on the client or data which do not need frequent refresh. The API makes it really easy to consume while they are backed by their own idiosyncrasies. Moving further, it would be a still better option to go for full fledged database storage on the client like IndexedDb which alleviates these issues of Web Storage. It’s a more of a balancing act wherein the ease of client side storage is purchased at the cost of performance. But for moderate complexity and volume, my opinion is that Web Storage is a potential candidate.

To report this post you need to login first.

Be the first to leave a comment

You must be Logged on to comment or reply to a post.

Leave a Reply