Back to Top

Storing Objects in Html5 Local Storage

Storing Objects in Html5 Local Storage

In HTML5, websites are able to store data locally within the user’s browser. This has been done with cookies before, but the Local Storage is a lot faster and way more secure. The data stored is not used for every server request, but is only processed when prompted. Also, unlike cookies, the Local Storage can cope with large amounts of data without affecting the overall website performance.

In this article, I will share my practice of using the Local Storage for optimizing the data load for websites. Also, at the end of the article, you will find helpful HTML, CSS and JavaScript code snippets for dealing with Local Storage.

What is Local Storage?

The “HTML5 Storage” is a specification named Web Storage, which was initially the part of the HTML5 specification. For uninteresting legal reasons, it was later branched out into its own specification. Today, browser vendors refer to it as “Local Storage” or “DOM Storage.”

The latest version of pretty much every browser supports HTML5 Storage (and yes, even the Internet Explorer).

Here is a full list of browsers that support HTML5 Storage:

  • IE 8+ (Note: IE 9 has a problem with numeric indexes and bracket notation, and doesn’t report quota errors using bracket notation);
  • FIREFOX 3.5+
  • SAFARI 4.0+
  • CHROME 4.0+
  • OPERA 10.5+
  • IPHONE 2.0+
  • ANDROID 2.0+

From your JavaScript code, you can access HTML5 Storage through the localStorage object on the global window object. Before you can use it, however, you should detect whether the browser supports it:

Instead of writing this function yourself, you can use Modernizr to detect support for HTML5 Storage:

HTML5 Storage is a way for web pages to store named key/value pairs locally, within the client web browser. Like cookies, this data persists even after you navigate away from the webpage, close your browser tab, exit your browser etc. Unlike cookies, this data is never transmitted to the remote web server, unless you intend so and send it manually.

Getting Around the Strorage

In HTML5 Storage, you store data based on a named key and retrieve that data with the same key. The data can be any type supported by JavaScript, including strings, Booleans, integers, or floats. However, the named key is a string, so the data is actually stored as a string. If you are storing and retrieving anything other than strings, you will need to use functions like parseInt() or parseFloat() to coerce your retrieved data into the expected JavaScript datatype.

Web Storage provides two objects for storing data on the client:

  1. window.localStorage – stores data with no expiration date;
  2. window.sessionStorage – stores data for one session (data is lost when browsing session ends that is, when the browser is closed).

Both objects have the same methods:

  • Storage.key() – When passed a number n, this method will return the name of the nth key in the storage.
  • Storage.getItem() – When passed a key name, will return that key’s value.
  • Storage.setItem() – When passed a key name and value, will add that key to the storage, or update that key’s value if it already exists.
  • Storage.removeItem() – When passed a key name, will remove that key from the storage.
  • Storage.clear() – When invoked, will empty all keys out of the storage.
  • and a similar property:

  • Storage.length – Returns an integer representing the number of data items stored in the Storage object (Note: read only).

Storing the Data

So let us test drive the HTML5 Storage now. There are two methods of storing the data in the web browsers – Session Storage and Local Storage. The first method only stores data for the current session. This means the data is cleared when the user closes their browser. The Local Storage, on the other hand, stores data permanently. For this test drive, we are going to use the HTML5 storage on the example of Local Storage.

Let us start with a “To Do List Application” as an example of storing an object in localStorage.

First, we have to create the HTML layout as shown below:

Now let us connect jQuery for the convenience of working with DOM:

Actually, you can use the CDN-version for the testing sake:

The next step is adding the script for creating tickets in our To Do Application:

Now let us check our Local Storage. We’ll find out that there is nothing there:

HTML5-Local-Storage

Nothing happens when we reload the page, either. Let us see how we can fix this. We can use the method setItem() in order to add key to the storage:

But here we have got a problem because the “ticket” key is not unique for every item in our “To Do List”, that is why only the last item will be saved in the localStorage (the setItem() method updates the key’s value that already exists).

In order to solve this problem we’ll just have to add the unique ID to every key in our list. Also, we will add the ability to display the already saved items in the localStorage and the ability to delete items from the list and from the Storage itself by clicking on the item:

So, we have programmed our HTML5 storage to store objects for us. Once again, doing so contributes greatly to the loading speed and overall performance of your web pages in every browser, and on every device.

Feel free to use the source code snippets for this operation shared on codepen.io. Test your ideas and happy coding!

Comments (2)

  1. Hello Mike,

    Nice tutorial, very well explanation. I have a query, is it possible to create a pagination using LocalStorage to list out data?

  2. Hi, Abhishek,
    In pagination, the amount of changing data is usually very large, and the space you can use in localStorage is relatively small (5-10 Mbytes, depending on the browser). So I would suggest only keeping the unchangeable data in the localStorage (such as, for example, user profile info, icons and fonts). This will allow the site to load faster on its first loading.
    Furthermore, during pagination, the data is transferred from the server by means of AJAX-queries, without the actual preloading of the page. This is a fairly quick process, so I guess using the Storage is not really required here 😉

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Popular Posts

How To Repair MySQL Table

Posted on 12 years ago

Bhumi

Inheritance in object-oriented PHP

Posted on 7 years ago

Bhumi