javascript用戶端解決方案 緩衝提供者

來源:互聯網
上載者:User

相信每一個開發人員都知道緩衝的重要性。從頭至尾有緩衝的後台(memcached,xcache等。) 來減輕db的壓力。對內容分髮網絡(CDN)緩衝中希望你的瀏覽器緩衝那些不止一次的載入資源。當然, 有用戶端緩衝,所以你不要重複昂貴的操作(即使是演算法或大量的運算)。

這是介紹的是一個不錯的javascript的方面的用戶端解決方案,可選配支援HTML5本機存放區器.

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

這裡使用try catch的主要原因是 儘管firefox支援該屬性,但是需要在about:config中設定並開啟,否則將會報錯。所以一個簡單的if else不能滿足需求。

下面我們將增加對象本機存放區機制的支援。這個技術是借鑒了Christopher Blizzard的一篇不錯的文章 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));
};
}

現在就到了我們的三個核心方法了,分別是 get, set, 和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];
}

};

如何運用?
注意在這篇文章的開始,就說了Cache Provider 是可選支配的本機存放區,首先然讓我們看一個沒有本機存放區的例子:

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

備忘:下次你調用類函數的時候, 將會用預先編譯好的Regex替代夠建造一個運算式。

再舉一個例子:比如 對於大的應用程式需要i18n,你可以緩衝一個編譯好的html字串進入本機存放區中。 複製代碼 代碼如下: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'));
});
}

除此之外,你開可以做很多外部資源緩衝到本地的事情,加油:)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.