Having discussed the basic differences between HTML5 and the previous versions of HTML, our main focus in this article would be discussing the data storage methods employed in HTML5. HTML5 maintains two basic methods for data storage: Permanent storage of data known as ‘localStorage’ and temporary storage of data for specific sessions known as ‘sessionStorage’. Previous versions of HTML did store data but that was done through cookies and two disadvantages govern data storage by cookies: First, cookies are unable to store large amount of data and second, data is stored with cookies with each request to the server. On the contrary, in HTML5, data is stored only when asked for, not with every subsequent request after establishing the connection with server.
The first method, the localStorage object stores the data with no time limit. The data will be available the next day, week, or year. For example, consider this piece of code:
1 2 3 4 5 6 7 8 9 10 11 |
<script type="text/javascript"> if (localStorage.pagecount) { localStorage.pagecount=Number(localStorage.pagecount) +1; } else { localStorage.pagecount=1; } document.write("Visits "+ localStorage.pagecount + " time(s)."); </script> |
In the above code, number of visitors to a certain web page are observed and stored. Since this count needs to be permanent and should remain intact after connection with server is lost, it is made permanent.
The second method, the sessionStorage object stores the data for one session. The data is deleted when the user closes the browser window. Consider the code below:
1 2 3 4 5 6 7 8 9 10 11 |
<script type="text/javascript"> if (sessionStorage.pagecount) { sessionStorage.pagecount=Number(sessionStorage.pagecount) +1; } else { sessionStorage.pagecount=1; } document.write("Visits "+sessionStorage.pagecount+" time(s) this session."); </script> |
The above code is used to store the number of times a specific user has visited a specific page during some particular sessions. After the connection is lost, that count is also lost since it was only for one session. Keeping in consideration the requirements of the developers and hosts, any of the above two methods can be utilized.