Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development

  • Print
  • + Share This
This chapter is from the book

Using web storage

Browser makers, and Apple in particular, have left us with a less than ideal situation when it comes to the browser cache. But they and the W3C have given us something else that almost makes up for it: the web storage API. Web storage provides a persistent data store for the browser, in addition to cookies. Unlike cookies, 5 MB is available per domain in a simple key-value store. On iOS, WebStorage stores the text as a UTF-16 string, which means that each character takes twice as many bytes. So on iOS the total is actually 2.5 MB.

Using the web storage API

Web storage is accessed from two global variables: localStorage and sessionStorage. sessionStorage is a nonpersistent store; it’s cleared between browsing sessions. It also isn’t shared between tabs, so it’s better suited to temporary storage of application data rather than caching. Other than that, localStorage and sessionStorage are the same.

Just like cookies, web storage access is limited by the same origin policy (a web page can only access web storage values set from the same domain) and if users reset their browsers all the data will be lost. One other small issue is that in iOS 5, web views in apps stored their web storage data in the same small space used for the browser cache, so they were hardly persistent. This has been fixed in iOS 6.

The web storage API is very simple. The primary methods are localStorage.getItem('key'); localStorage.setItem('key', 'value'). key and value are stored as strings. If you try to set the value of a key to a non-string value it will use the JavaScript default toString method, so an object will just be replaced with [object object].

Additionally you can treat localStorage as a regular object and use square bracket notation:

var bird = localStorage['birdname'];

localStorage['birdname'] = 'Gull';

Removing items is as simple as calling localStorage.removeItem('key'). If the key you specify doesn’t exist, removeItem will conveniently do nothing.

In addition to storing specific information, localStorage is a great tool for caching. In this next section, we’ll use the Flickr API to fetch a random photo for Birds of California, and use localStorage as a transparent caching layer to greatly improve the performance of the random image picker on future page loads.

Using web storage as a caching layer

For the Birds of California site, we can make things a little more exciting for users by incorporating a random image from Flickr, rather than a predefined image. This will sacrifice some of the gains we made in the last chapter in trimming images down to size, in exchange for developer convenience.

We’ll use the Flickr search API to find Creative Commons–licensed photos of birds. Listing 4.1 is a simple JavaScript Flickr API module that uses JSONP to fetch data. For the sake of brevity the code is not included here, but it’s available for download from the website. Let’s use this module to grab some images related to the California Gull.

Listing 4.1. Fetching the Flickr data

//a couple of convenience functions
var $ = function(selector) {
 return document.querySelector(selector);

var getEl = function(id) {
 return document.getElementById(id);

var flickr = new Flickr(apikey);
var photoList;


   text:'Larus californicus',

 function(data) {
   photoList =;

As you can see, the API takes a method ( and some parameters. This will hopefully give us back as many as 50 photos of Larus Californicus.

In Listing 4.2, the updatePhoto function takes the list, grabs a random photo from the list, and updates the image, the links, and the attribution.

Listing 4.2. Updating the photo

function updatePhoto() {
  var heroImg = document.querySelector('.hero-img');

  //shorthand for "random member of this array"
  var thisPhoto = photoList[Math.floor(Math.random() * photoList.length)];
          = 'url('+ thisPhoto.url_z + ')';

  //update the link
  getEl('imglink').href =
     '' +
     thisPhoto.owner +

  //update attribution
  var attr = getEl('attribution');
  attr.href = ''
       + thisPhoto.owner;

  attr.innerHTML = thisPhoto.ownername;


Add this script (with the Flickr API module) to the Birds of California page with a valid Flickr API key and the bird hero image will dynamically update to a random option from the search results list. With no changes to the HTML and CSS from before, however, the user will see the original gull photo, and then a moment later it will be replaced with the result from the API. On one hand, this provides a fallback in case of JavaScript failure for the image. But on the other hand, it doesn’t look very nice, and we’ll go ahead and say the image is an enhancement to the main content, which is the text.

With that in mind, let’s create a null or “loading” state for the links and caption, as shown in Listing 4.3.

Listing 4.3. Hero image null state

<div class="hero-shot">
  <a id="imglink" href="#">
  <span class="hero-img"></span></a>
  <p class="caption">
    Photo By <a id="attribution" href="#">...</a>

While the data is loading the user needs some indication that something’s happening, just so she knows things aren’t broken. Normally a spinner of some kind is called for, but in this case let’s just add the text “loading” and make the image background gray until it’s ready:

//show the user we are loading something....
var heroImgElement = $('.hero-img'); = '#ccc';
heroImgElement.innerHTML = '<p>Loading...</p>';

//Then inside updatePhoto I'll remove the loading state:
heroImgElement.innerHTML = '';

So, now we have a pretty nice random image, with a loading state (Figure 4.1). However, we’re making users wait every time they visit for a random image from a list that probably doesn’t change that much. Not only that, but having a very up-to-date list of photos isn’t all that important because we just want to add variety, not give up-to-the-minute accurate search results. This is a prime candidate for caching.

Figure 4-1

Figure 4.1. The loading state.

If something is cacheable, it’s generally best to abstract away the caching, otherwise the main logic of the application will be cluttered with references to the cache, validation checks, and other logic not relevant to the task at hand. For this call we’ll create a new object to serve as a data access layer, so that rather than calling the Flickr API object directly, we’ll call the data layer, like so:

birdData.fetchPhotos('Larus californicus', function(photos) {
 photoList = photos;

Because all we ever want to do is search for photos and get back a list, we can hide the Flickr-specific stuff inside this new API. Not only that, but by creating a clean API we can, in theory, change the data source later. If we decide that a different API produces better photo results, we can change the data layer without making changes to any consumers. In this case the key feature is caching. We want to cache API results locally for one day, so that the next time the user visits she’ll still get a random photo, but she won’t have to wait for a response from the Flickr API.

Creating the caching layer

The fetchPhotos method will first check if this search is cached, and whether the cached data is still valid. If the cache is available and valid, it will return the cached data, otherwise it will make a request to the API and then populate the cache after firing the callback.

First, we’ll set up a few variables, as shown in Listing 4.4.

Listing 4.4. A caching layer

window.birdData = {};

var memoryCache = {};

var CACHE_TTL = 86400000; //one day in seconds
var CACHE_PREFIX = 'ti';

The memoryCache object is a place to cache things fetched from localStorage, so if those items are requested again in the same session they can be returned even faster; fetching data from localStorage is much slower than simply getting data from memory, without including the added cost of decoding a JSON string (remember, localStorage can only store strings). We’ll talk more about CACHE_PREFIX and CACHE_TTL shortly.

The first thing we need is a method to write values into cache. We’ll cache the response from the Flickr search, but wrap the cached value inside a different object so we can store a timestamp for a cache so that it can be expired.

function setCache(mykey, data) {

 var stamp, obj;

 stamp =;

 obj = {
   date: stamp,
   data: data

 localStorage.setItem(CACHE_PREFIX + mykey, JSON.stringify(obj));
 memoryCache[mykey] = obj;

We’re using CACHE_PREFIX for each of the keys to eliminate the already small chance of collisions. It’s possible that another developer on the Birds of California site might decide to use localStorage, so just to be on the safe side we’ll prefix our keys. The date value contains a timestamp in seconds, which we can use later to check if the cache has expired. We’ll also add the value to the memory cache for quicker access to it if it’s fetched again during the same session. We’ll use the “setItem” notation for localStorage; this is much clearer than bracket notation—another developer will see right away what is happening, rather than thinking that this is a regular object.

The next function is getCached, which returns the cached data if it’s available and valid, or false if the cache is not present or expired (the caller really doesn’t need to know which):

//fetch cached date if available,
//returns false if not (stale date is treated as unavailable)
function getCached(mykey) {

  var key, obj;

  //prefixed keys to prevent
  //collisions in localStorage, not likely, but
  //a good practice
  key = CACHE_PREFIX + mykey;

 if(memoryCache[key]) {

   if(memoryCache[key].date - > CACHE_TTL) {
      return false;

   return memoryCache[key].data;

 obj = localStorage.getItem(key);

 if(obj) {
    obj = JSON.parse(obj);

    if ( - > CACHE_TTL) {
      //cache is expired! let us purge that item
      return false;
    memoryCache[key] = obj;

This function checks the cache in layers. It starts with the memory cache, because this is the fastest. Then it falls back to localStorage. If it finds the value in localStorage, then it makes sure to also put that value into the memoryCache before returning the data. If no cached value is found, or one of the cached values has expired, then the function returns false.

Next up is the actual fetchPhotos function that encapsulates the caching. All it has to do now is fetch the cached value for the query. If that value is false, then it executes the API method and caches the response. If it is true, then the callback function is called immediately with the cached value.

// function to fetch CC flickr photos,
// given a search query. Results are cached for
// one day
function fetchPhotos(query, callback) {
 var flickr, cached;

 cached = getCached(query);

 if(cached) {
 } else {

    flickr = new Flickr(API_KEY);



             function(data) {

                //set the cache after the
                //callback, so that it happens after
                  //any UI updates that may be needed
                setCache(query, data);


window.birdData.fetchPhotos = fetchPhotos;

Now the data call is fully cacheable, with a simple API.

Managing localStorage

This is just the beginning for localStorage. Unlike the browser cache, localStorage gives you full manual control. You can decide what to put in, when to take it out, and when to expire it. Some websites (like Google) have actually used localStorage to cache JavaScript and CSS explicitly. It’s a powerful tool, so powerful that 5 MB starts to feel a little small sometimes. What do you do when the cache is full? How do you know if the cache is full?

First of all, we can treat localStorage as a normal JavaScript object, so JSON.stringify (localStorage) will return a JSON representation of localStorage. Then we can apply an old trick to figure out how many bytes that uses, including UTF-8 multi-byte characters: unescape(encodeURIcomponent('string')).length, which gives us the size of string in bytes. We know that 5 MB is 1024 * 1024 * 5 bytes, so the available space can be found with this:

1024 * 1024 * 5 - unescape(encodeURIComponent(JSON.stringify(localStorage))).length

If you want to know if you’ve run out of space, WebKit browsers, Opera mobile and Internet Explorer 10 for Windows Phone 8 will throw an exception if you’ve exceeded the available storage space; if you’re worried, you can wrap your setItem call in a try/catch block. When you’ve run out of storage you can either clear all the values your app has written with localStorage.clear, or keep a separate list in localStorage of all the data you cache and intelligently clear out old values.

  • + Share This
  • 🔖 Save To Your Account

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive:

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020