Comparing Local Storage and Session Storage (Should know)

At the beginning of this book, we took a look at how you can use Local Storage to store persistent information on a client computer, which remains there even when the browser is closed. That's great, but isn't it a little overkill for instances such as shopping carts? You'd be right – we don't need to store information about purchases forever; indeed, information should only be stored for the duration of the current session. In this recipe, we're going to take another look at Session Storage, to see how it stacks up against LocalStorage.

How to do it...

In the following steps, we will take a look at how it works and stacks up against Local Storage:

  1. Let's begin by creating a new HTML document. Add the following code snippet and save it as sessionvlocaldemo.html:
    <!DOCType html>
    <html>
    <head>
    </head>
    <body>
      <div id="content">
    </div>
    </body>
    </html>
  2. This code needs to use jQuery in order to work, so let's go ahead and add it. We want to make sure the results on screen look presentable, so we'll add in some basic styling for good measure:
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.min.js"></script>
    <style type="text/css">
      #content { width: 400px; padding: 10px; 
      margin-left: auto; margin-right: auto;
      margin-top: 5%; border: 1px solid #c4c4c4; }
    </style>
  3. We need to add our script, which will manage the Session Storage requests. Begin with the event handler that manages how many times we click on the request button:
      <script type="text/javascript">
      function clickCounter()
      {
        if(typeof(Storage)!=="undefined") {
        if (sessionStorage.clickcount) { 
          sessionStorage.clickcount=Number
          (sessionStorage.clickcount)+1;
        } else {
          sessionStorage.clickcount=1;
        }
        document.getElementById("result").innerHTML=
        "You have clicked the button " + 
        sessionStorage.clickcount + " time(s).";
        } else {
          document.getElementById("result").innerHTML=
          "Sorry, your browser does not support web 
          storage...";
        }
      }
  4. The following function gets the requested data and pushes it into the localStorage area:
      function storeItem() {
        var item = $('#item').val();
        var items = localStorage.getItem('myItems'),
        if (items != null) {
          items = JSON.parse(items);
        } else {
          items = new Array();
        }
        items.push(item);
        localStorage.setItem('myItems', JSON.stringify(items));
        refresh();
      }
  5. Then, we need to refresh the screen to update values on the screen:
      function refresh() {
        var items = localStorage.getItem('myItems'),
        var ul = $('ul'),
        ul.html(''),
        if (items != null) {
          items = JSON.parse(items);
          $(items).each(function (index, data) {
            ul.append('<li>' + data + '</li>'),
          });
        }
      }
  6. The following script calls the refresh function that we've just set up:
      $(function () {
        refresh();
      });
      </script>
  7. Finally, we need to provide the means to request data from the user for both Session Storage and Local Storage:
      <p><b>SessionStorage Demo:</b></p>
      <p><button onclick="clickCounter()" type="button">
      Click me!</button></p>
      <div id="result"></div>
      <p>Click the button to see the counter increase.</p>
      <hr>
      <p><b>LocalStorage Demo:</b></p>
      <p>Enter item:</p>
      <input type="text" id="item" />
      <input type="button" value="store" onclick=
      "storeItem()" />
      <br />
      <ul></ul>
  8. You should see something similar to the following screenshot, when previewing in a browser:
    How to do it...

How it works...

At the heart of Session Storage, there is actually very little difference compared to that of Local Storage. Both work on the same basis of setting and getting a named key/value pair within the browser's storage area. Clicking on the SessionStorage button will increase the counter ad to infinitum. It will be reset as soon as you refresh your browser window. In contrast, adding any entries to the LocalStorage option will store the values; these will remain stored, irrespective of any browser refresh.

If you need information to remain on the browser after it has been closed or restarted, you should use Local Storage. If, however, you're only looking to keep values for the duration of a single session, Session Storage is the better option.

There's more...

Now that we have had an opportunity to look at Session Storage, let's dig into how both methods work in more detail.

Both Local and Session Storage work using the same methods:

Type

Name and arguments

Purpose

string

key(int)

Returns the name of a key at the index in the argument

string

getItem(string key)

Returns the value of the key

void

setItem(string key, string data)

Assigns a value to a key

void

removeItem(string key)

Removes the key whose name is in the argument

void

clear()

Clears the storage space and removes all keys

long

length()

Number of items stored

The Storage API has been defined so that each of the get, set, and remove methods are known as getters, setters, and deleters. To see what I mean, take a look at the following two examples:

var myVar = sessionStorage.getItem('myKey'),
sessionStorage.setItem('myKey', 'myValue'),

These two methods get and set the information into the myKey value within the localStorage area of the browser as a sessionStorage key/value pair. However, you could equally write the following:

sessionStorage.myKey = 'myValue';
var myVar = sessionStorage.myKey;

The preceding code would achieve the same result and is probably a little more readable too! The same applies to localStorage:

localStorage.setItem('myKey', 'myValue'),
var myVar = localStorage.getItem('myKey'),

You could write this as follows:

localStorage.myKey = 'myValue';
var myVar = localStorage.myKey;

The preceding code will achieve the same result.

Now we've seen how Session Storage works. We will now see some more differences between Session Storage and Local Storage. Before doing so, we're going to take a look at a theoretical example of how you could approximate the effect of Session Storage if you don't have any access to jQuery or a library such as Modernizr, or to a more recent browser. It will look ugly, but there is a reason for showing you this. All will become clear as we go through the next recipe.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset