Javascript cache provider

Source: Internet
Author: User

I believe that every developer knows the importance of caching. Cache backend (such as memcached and xcache) from the beginning to the end .) To reduce the pressure on the database. You want your browser to cache more than once loaded Resources in the Content Delivery Network (CDN) cache. Of course, there is a client cache, so you should not repeat expensive operations (Even algorithms or a large number of operations ).

This is a good javascript client solution. You can choose to support 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 for using try catch here is that although firefox supports this attribute, you must set and enable it in about: config. Otherwise, an error will be reported. Therefore, a simple if else cannot meet the requirements.

Next we will add support for the object local storage mechanism. This technology is used for reference.Christopher Blizzard's article Saving data with local storage-for which those who didn't know, you canOnlyStorestring'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 we have three core methods: 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 to use it?

Note that at the beginning of this article, the Cache Provider is an optional local storage. First, let's look at an example without 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 call a class function, a pre-compiled regular expression will be used to replace the regular expression.

For example, if i18n is required for a large application, You Can cache a Compiled html string and store it locally.

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

In addition, you can cache a lot of external resources locally. Come on :)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.