google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank
Guest, register






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.


Free iPage Web Hosting for First Year NOW



If you're still looking for a reliable web host provider with affordable rates, why you don't take a little of time to try iPage, only with $1.89/month, included $500+ Free Extra Credits for the payment of 24 months ($45)?

Over 1,000,000+ existisng customers can not be wrong, definitely you're not, too! More important, when you register the web hosting at iPage through our link, we're going to be happy for resending a full refund to you. That's awesome! You should try iPage web hosting for FREE now! And contact us for anything you need to know about iPage.
Try iPage for FREE First Year NOW

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 ;)

iPhoneKer.com
Save up to 630$ when buy new iPhone 15

GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project

https://tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools

chatGPTaz.com, chatGPT4.win, chatGPT2.fun, re-chatGPT.com
Talk to ChatGPT by your mother language

Dall-E-OpenAI.com
Generate creative images automatically with AI

AIVideo-App.com
Render creative video automatically with AI

JavaScript by day


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web