facebook@jsbanktwitter@js_bankgoogle+javascriptbanknewsletterrss@jsbank
Guest, register






gomymobi.com - Free Business Site Builder & Platform

JavaScript Caching in HTML5 Every web developer/web coder/web programmer should know the importance of JavaScript caching for web performance. With technology specifications of old HTML versions, we can only store JavaScript browser caches in cookie on client side, or do it on server side with session/other web storage solutions with files.

However in the new version of HTML - HTML5; besides the capabilities of offline cache (see more new features of HTML5 in HOT New JavaScript APIs with HTML5), HTML5 also give us the abilities of local storage to speed up the web performance.

This JavaScript article tutorial shows you some basic concepts and JavaScript code examples to build web applications with cache in HTML5. Please go to the full post page for details.


Every developer knows the importance of caching. From end to end you have caching on the backend (memcached, xcache, etc.) to prevent your databases being lit on fire, edge caching on content delivery networks (CDN's) in hopes that your browser will cache assets it sees more than once. And of course client-side caching so you don't repeat expensive operations (albeit algorithmically or high volume repitions). Here is a solution in JavaScript to help you out with the latter, with optional support for HTML5 Local Storage.

Starting Simple

function CacheProvider() {
  // values will be stored here
  this._cache = {};
}

Feature detect on local storage

try {
  CacheProvider.hasLocalStorage = ('localStorage' in window) && window['localStorage'] !== null;
} catch (ex) {
  CacheProvider.hasLocalStorage = false;
}

The main reason we use try / catch is because despite Firefox supporting it, it can be disabled in your about:config settings and an error will be thrown. A simple if / else will not work.

Next we'll add support for storing objects into local storage. This technique was borrowed from Christopher Blizzard in his excellent post Saving data with local storage - for which those who didn't know, you can only store string's into local storage. Thus we have this...

in / out JSON parsing

if (CacheProvider.hasLocalStorage) {
  Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
  };

  Storage.prototype.getObject = function(key) {
    return JSON.parse(this.getItem(key));
  };
}

Now for our three core methods, we'll have get, set, and clear.

Core class functionality

CacheProvider.prototype = {

  /**
     * {String} k - the key
     * {Boolean} local - get this from local storage?
     * {Boolean} o - is the value you put in local storage an object?
     */
  get: function(k, local, o) {
    if (local && CacheProvider.hasLocalStorage) {
      var action = o ? 'getObject' : 'getItem';
      return localStorage[action](k) || undefined;
    } else {
      return this._cache[k] || undefined;
    }
  },

  /**
     * {String} k - the key
     * {Object} v - any kind of value you want to store
     * however only objects and strings are allowed in local storage
     * {Boolean} local - put this in local storage
     */
  set: function(k, v, local) {
    if (local && CacheProvider.hasLocalStorage) {
      if (typeof v !== 'string') {
        // make assumption if it's not a string, then we're storing an object
        localStorage.setObject(k, v);
      } else {
        try {
          localStorage.setItem(k, v);
        } catch (ex) {
          if (ex.name == 'QUOTA_EXCEEDED_ERR') {
            // developer needs to figure out what to start invalidating
            throw new Exception(v);
            return;
          }
        }
      }
    } else {
      // put in our local object
      this._cache[k] = v;
    }
    // return our newly cached item
    return v;
  },

  /**
     * {String} k - the key
     * {Boolean} local - put this in local storage
     * {Boolean} o - is this an object you want to put in local storage?
     */
  clear: function(k, local, o) {
    if (local && CacheProvider.hasLocalStorage) {
      localStorage.removeItem(k);
    }
    // delete in both caches - doesn't hurt.
    delete this._cache[k];
  }

};

How does this work?

Note in the beginning of this post, said Cache Provider was to have optional support for local storage (although it appears to be most of the point). First let's look at an example sans-local-storage.

getElementsByClassName

var cache = new CacheProvider;

window.getElementsByClassName = getElementsByClassName || function(c) {
  var reg = cache.get(c) || cache.set(c, new RegExp("(?:^|\\s+)" + c + "(?:\\s+|$)"));
  var elements = document.getElementsByTagName('*');
  var results = [];
  for (var i = 0; i < elements.length; i++) {
    if (elements[i].className.match(reg)) {
      results.push(elements[i]);
    }
  }
  return results;
};

Note the next time you work with the same class - it work with a precompiled regular expression instead of constructing a new one.

As another example, for large apps that require i18n, you could cache the compiled HTML strings into local storage.

var i18nCache = new CacheProvider;

if (i18nCache.get('topnav')) {
  $('#nav').html(i18nCache.get('topnav'));
} else {
  ajax('top-nav.tmpl', function(html) {
    i18nCache.set('topnav', html);
    $('#nav').html(i18nCache.get('topnav'));
  });
}

Other than that, have a play, do some caching, and outsource your resources to your users browser. cheers ;)

JavaScript by day


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web