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:
1 2 3 4 5 6 7 8 9 | try { return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { return false; } } |
Instead of writing this function yourself, you can use Modernizr to detect support for HTML5 Storage:
1 2 3 4 5 6 7 8 | if (Modernizr.localstorage) { // code for localStorage/sessionStorage } else { // no native support for HTML5 storage // try a third-party solution as dojox.storage or other } |
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:
- window.localStorage – stores data with no expiration date;
- 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.
- Storage.length – Returns an integer representing the number of data items stored in the Storage object (Note: read only).
and a similar property:
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:
1 2 3 4 5 6 | <div id="to-do-app"> </div> |
Now let us connect jQuery for the convenience of working with DOM:
1 2 3 | <script src="jquery.js"></script> |
Actually, you can use the CDN-version for the testing sake:
1 2 3 | <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> |
The next step is adding the script for creating tickets in our To Do Application:
1 2 3 4 5 6 7 8 9 10 11 12 13 | var toDoList = $('.to-do-list'); $('#to-do-app input').on('keydown', function(e){ if(e.keyCode != 13) //event of keypress "enter" return; var ticket = e.target.value; //assign the variable for our entered value e.target.value = ""; //reset the value if(ticket.length > 0){ //here we add our entered value into To Do List $('<li></li>').addClass('to-do-item').text(ticket).appendTo(toDoList); } }); |
Now let us check our Local Storage. We’ll find out that there is nothing there:
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:
1 2 3 | localStorage.setItem('ticket', ticket); |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | var toDoList = $('.to-do-list'); //use mask to protect from interference with the other keys from other plugins var itemMask = 'ticket_'; $('#to-do-app input').on('keydown', function(e){ if(e.keyCode != 13) return var ticket = e.target.value; e.target.value = ""; if(ticket.length > 0){ var newID = 0; //cut new ID from attr('data-itemid') var currentID = $(elem).attr('data-itemid').slice(7); if(currentID > newID) newID = currentID; }); newID++; localStorage.setItem(itemMask+newID, ticket); $('<li></li>').addClass('to-do-item') .attr('data-itemid', itemMask+newID) //save the unique ID for every item .text(ticket) .appendTo(toDoList) } }); //remove item from localStorage and from list by click on it $(document).on('click', '.to-do-item', function(e){ localStorage.removeItem($(this).attr('data-itemid')); $(this).remove(); }); //function that displays already saved items in localStorage (function (){ if (localStorage.length){ for(var i=0; i<localStorage.length; i++){ var key = localStorage.key(i); if(key.indexOf(itemMask) == 0){ $('<li></li>').addClass('to-do-item') .attr('data-itemid', key) .text(localStorage.getItem(key)) .appendTo(toDoList); } } } }()); |
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)