How and when to use HTML5 LocalStorage API?

HTML5
HTML5

Recently I had a need to use HTML5 LocalStorage API in my web application project check my reference. The requirement was to save the vertical scroll position of window when a user drills down to low level details by navigating to other view. I didn’t wanted to use cookies because they are sent on every request to the server and I have no need to send this detail to the server as it is just related to client.

Then I was left with LocalStorage and SessionStorage as options. I found that SessionStorage is not maintained when the page reloads and when the browser is closed.  So, I opted to use LocalStorage API for this use case and came up with the code below which is a localStorageWrapper module that can be accessed as a module when using RequireJS (a module loader). A client consuming this wrapper is able to set, get, check the existence of a key and clear all the items in client’s localStorage. An item that can be save is made up of a key and a value. This value can be just a string or an javascript object that can be JSON stringified and then saved. This can be seen in the set function of the localStorageWrapper module below.

When using these fancy new HTML5 APIs, one should care about the browser support. You can use CanIuse website to check it. This is a very good resource to check support for everything and anything related to web.

To properly provide graceful degradation, you can use Modernizr to check if client supports a particular HTML5 feature.
When using Modernizr, the client code consuming the above module looks like:

Siddharth Pandey

Siddharth Pandey is a Software Engineer with thorough hands-on commercial experience & exposure to building enterprise applications using Agile methodologies. Siddharth specializes in building, managing on-premise, cloud based real-time standard, single page web applications (SPAs). He has successfully delivered applications in health-care, finance, insurance, e-commerce sectors for major brands in the UK. Other than programming, he also has experience of managing teams, trainer, actively contributing to the IT community by sharing his knowledge using Stack Overflow, personal website & video tutorials.

You may also like...

Advertisment ad adsense adlogger