Javascript client solution cache provider

Source: Internet
Author: User
Tags try catch

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 if Algorithm Or a large number of operations ).

This is a good JavaScript client solution. You can choose to support HTML5 local storage.

Starting simpleCopyCodeThe Code is as follows: function cacheprovider (){
// Values will be stored here
This. _ cache = {};
} Feature detect on Local Storage
Try {
Cacheprovider. haslocalstorage = ('localstore' in window) & window ['localstore']! = 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 a good reference for Christopher blizzard.ArticleSaving 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 ParsingCopy codeThe Code is as follows: 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 functionalityCopy codeThe Code is as follows: 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;
}< BR >},

/**
* {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 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;
}< BR >}} else {
// put in our local object
This. _ cache [k] = V;
}< br> // 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:

GetelementsbyclassnameCopy codeThe Code is as follows: 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.

Another example: for large applicationsProgramI18n is required. You can cache a Compiled HTML string and store it locally.Copy codeThe Code is as follows: var i18ncache = new cacheprovider;

If (i18ncache. Get ('topnav ')){
Certificate ('{nav'}.html (i18ncache. Get ('topnav '));
} Else {
Ajax ('top-nav. tmpl', function (HTML ){
I18ncache. Set ('topnav', HTML );
Certificate ('{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.