With HTML 5 now Web pages can store data locally on the user's browser so that performance can be improved. Local storage can make page load faster. Web storage works using cookies. However, Web Storage is more secure and faster than cookies. Data stored using cookies is server request dependent. In other word if a data is stored against a server request (action) then that data will be available for that for that server request (action) not for the other server request (action). Browser can be store large volumes of data, without affecting the website performance.
On the web page data is stored in Key/value pairs and data can be access by the web page.
For efficiency there are two types objects that can be used for storing data on the client
- Local Storage: stores data with no time limits it will never expire.
- Session Storage - stores data for one session (for example- We can use session storage object for login information of a user).
If you want to use “web storage” methodology then first check if the browser supports session and local Storage.
Local storage stores data with no time limits, hence the data will never be expiring. In other words stored data will not be deleted when the browser is closed or system is restarted and data will always be available (for example- if you want to store the current city of the s user presuming that it will never change i.e. next day, week, month or years city remains the same). You can use the following code to store the city in the local storage.
document.getElementById("result").innerHTML="City: "+ localStorage.city;
Make a localStorage key and value pair with key="city" and value="melbourne"
Retrieve the value of the "city" key and insert it into the element with id="result"
The following example will count the total number of times a user has been clicked a button. In this code the value string will be converted to a number and counter will be increase.
document.getElementById("result").innerHTML="You have been total clicked on button " + localStorage.clickcount + " time(s).";
The session Storage Object
A sessionStorage object works as a localStorage object, but the difference it has with localStorage object is that session data will be deleted when the user closes their browser window.
The following example will be counts the number of times when a user has been clicked on button, in the working session:
document.getElementById("result").innerHTML=" You have been total clicked on button " + sessionStorage.clickcount + " time(s) in this session.";