MANAGING LOCAL DATA WITH THE HELP OF WEB STORAGE - A SIMPLE START TO JQUERY, JAVASCRIPT, AND HTML5 FOR BEGINNERS (2014

A SIMPLE START TO JQUERY, JAVASCRIPT, AND HTML5 FOR BEGINNERS (2014)

CHAPTER 10: MANAGING LOCAL DATA WITH THE HELP OF WEB STORAGE

Most of the topics discussed in the previous section focused on improving the performance of the websites and the services that it provides its customers. Therefore, handling information or data has been restricted to the data that is transferred between the client and server. In such a case, the server needs to wait for the complete round trip to occur. This involves cost overheads.

In order to address this issue, most modern day browsers have started supporting web or DOM storage, which allows storage of some data at the client level. This chapter provides an overview of storage mechanisms used and how they can be used to improve the performance of the system in this regard.

Introduction to Web Storage

In most web application, a server side storage solution like SQL Database Server is implemented. This may be an attempt to kill a mosquito with a sword. You don’t need such a huge storage solution as storing small bits of information at the browser level could have solved your purpose.

Http cookies has been the most preferred and commonly used form of data storage at the browser level. In fact, it is used by most browsers for storing user information. The cookie value can be set in the following manner:

function setCookieValue(cName, cValue, daysToExpire) {

var daysToExpire = new Date();

daysToExpire.setDate(daysToExpire.getDate() + daysToExpire);

cValue = cValue + "; expires=" + daysToExpire.toUTCString();

document.cookie = cName + "=" + cValue;

}

The cookie value can be retrieved using the following code:

function getCookieValue(cName)

{

var cookie = document.cookie.split(";");

for (var i = 0; i < cookie.length; i++) {

var cookies = cookie[i];

var indexVal = cookies.indexOf("=");

var keyVal = cookies.substr(0, index);

var actualVal = cookies.substr(index + 1);

if (keyVal == cName)

return actualVal;

}

}

The last segment of code, shown below, illustrates how cookies can be used.

setCookie('fName', Clark, 1);

var fName = getCookie('fName');

You can also use the cookie plug-in available in jQuery, which can be used in the following manner:

$.cookie('fName', 'Clark');

var fName = $.cookie('fName');

Although, cookies are extensively used, they pose some serious issues like overhead and capacity limitation. Some alternatives available include:

● Google Gears

● User Data

● Java Applets

● Flash Player

These options are better cookies and addresses its limitations, but they suffer from some issues, which include:

● Pug-in is required

● User can block them

● Not useful for corporate users

● They are vendor-specific.

HTML5 Storage

Although, these tools offers some good, yet potentially improvable solutions, HTML5 has come up with some innovative tools in their attempt to provide a comprehensive solution.

Web storage

The simplest form of storing data over the web is web storage, in which key-value pairs are stored.

Web SQL database

If the application requires a full relational database, then Web SQL database is also available for us.

IndexedDB

This is a NoSQL database that is seen as a good alternative to its relational counterpart. It is considered to be a good option for complex database requirements.

Filesystem API

This is the preferred form of data storage is the data is of larger data types like images, audios and videos.

In all of the above mentioned types of data storage, the data is tied to the URL. Therefore, this data cannot be accessed by other websites. This is an important consideration when multiple websites are hosted on a shared domain.

Exploring localStorage

LocalStorage is one of the two storage mechanisms used for data storage. It is basically a Storage Object, which is stored as a global variable. The biggest advantage of using this mechanism is that the API provided for reading and writing data is simple and easy to use.

How to Use localStorage Object Reference

The attributes and methods available include:

setItem(key, value)

It is a method that is used to set a value with the help of an associated key. The syntax for this operation is:

localStorage.setItem('fName', $('#fName').val());

getItem(key)

It is a method that is used to get a value associated to the specified key. The syntax for this operation is:

var fName = localStorage.getItem('fName');

If no value is set, then null is returned.

removeItem(key)

It is a method that is used to remove a value associated to the specified key. The syntax for this operation is:

localStorage.removeItem('fName');

clear()

Removes all items from the local storage. Its syntax is:

localStorage.clear();

length

It is the property that returns the number of entries in the storage.

var count = localStorage.length;

key(index)

This method is used for finding the key associated with the given value. The syntax for this operations is:

var keyValue = localStorage.key(1);

One of the biggest benefits of using this storage mechanism is that it is supported by most modern browsers, unlike other storage mechanisms, which are supported by only a few browsers. Although, this mechanism is supported by most web browsers, it is a good idea to check it before using it. If the first reference to this storage returns null, then it can be assumed that the storage mechanism is not supported. In addition to this, you can also use the construct given below for this purpose:

function isWSSupported() {

return 'localStorage' in window;

}

if (isWSSupported()) {

localStorage.setItem('fName', $('#fName').val());

}

In addition to this, you can also use the Modernizr javascript library for the checking purpose. It is worth mentioning here that this type of web storage allows 5MB of web storage, as against the 4KB of web storage allowed by cookies. When the storage space is exceeded, an exception for the same is thrown by the system.

Although, web storage allows storage of strings only, but you can also store complex objects with the help of JSON utility methods.

How to Use Short-term Persistence with sessionStorage

SessionStorage is also a Storage Object, with the same attributes and methods as localStorage. The only difference between the two storage mechanisms is that sessionStorage stores data for the session only. If the browser window is closed, the data will no longer be available for use.

Issues Related to sessionStorage and localStorage

Some of the issues related to these two storage mechanisms include:

1. Simultaneous reading and writing of the hard drive.

2. Slow searching capabilities.

3. No support for transactions.

How to Handle Storage Events

Synchronization is the biggest challenge faced in the implementation of web storage. In order to deal with this issue, you can subscribe to storage events, which can notify you about any changes that may have been occurred. When you subscribe to a StorageEvent, you get access to the following properties:

● newValue

● oldValue

● url

● key

● storageArea

Unlike other events, cancelling or bubbling a StorageEvent is not allowed. You can subscribe to an event using the following construct:

function respond (exc) {

alert(exc.newValue);

}

window.addEventListener('storage', respond, false);

This event can be triggered using the following operation:

localStorage.setItem('name', Clark);

You can also bind to these events with the help of jQuery.