JavaScript Client solution cache provider _javascript Tips

Source: Internet
Author: User
Tags try catch
Believe that every developer knows the importance of caching. There is a cached background (Memcached,xcache, etc.) from beginning to end. ) to reduce the pressure on db. In the Content distribution network (CDN) cache, you want your browser to cache those loaded resources more than once. Of course, there is client-side caching, so you don't have to repeat expensive operations (even algorithms or a lot of operations).

This is an introduction to a good JavaScript aspect of the client solution that can be matched to support HTML5 local storage.

Starting simple
Copy Code code as follows:

function Cacheprovider () {
Values would be stored here
This._cache = {};
}feature detect on the 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 property, it needs to be set up and turned on in About:config, otherwise it will be an error. So a simple if else does not meet the requirements.

Below we will add support for the object local storage mechanism. This technique is borrowed from the Christopher Blizzard a good article saving data with the local storage–for which those the WHO didn ' t know, your can only store String ' s into the local storage. Thus we have this ...

In/out JSON Parsing
Copy Code code 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 it's our three core methods, which are get, set, and clear.

Core class Functionality
Copy Code code as follows:

Cacheprovider.prototype = {

/**
* {String} k-the key
* {Boolean} local-get this to local storage?
* {Boolean} o-is the ' value ' in the ' 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 isn't 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 on our local object
This._cache[k] = v;
}
Return to our newly cached item
return v;
},

/**
* {String} k-the key
* {Boolean} local-put this in local storage
* {Boolean} O-is This is the object you want to put in the 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?
Notice at the beginning of this article that cache Provider is an optional local storage, and first let's look at an example without local storage:

Getelementsbyclassname
Copy Code code 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, you will be able to build an expression with a precompiled regular expression.


One more example: for large applications that require i18n, you can cache a compiled HTML string into the local store.
Copy Code code as follows:

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 do a lot of external resources to cache to local things, refueling:

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.