IT技术博客大学习 共学习 共进步
全部 移动开发 后端 数据库 AI 算法 安全 DevOps 前端 设计 开发者

javascript 缓存提供程序

UED TEAM 2010-07-15 08:43:00 累计浏览 2,970 次
本机暂存

相信每一个开发者都知道缓存的重要性。从头至尾有缓存的后台(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;
 

};

备注:下次你调用类函数的时候, 将会用预先编译好的正则表达式替代够建造一个表达式。

再举一个例子:比如 对于大的应用程序需要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'));
   });
 }

除此之外,你开可以做很多外部资源缓存到本地的事情,加油:)

来源:http://article.yeeyan.org/view/ibaihu/115921

同分类推荐文章

  1. translateZ() (2026-06-25 21:18:56)
  2. translateY() (2026-06-25 21:17:56)
  3. translateX() (2026-06-25 21:16:01)

查看更多 前端 文章 →

建议继续学习

  1. JQuery实现Excel表格呈现 (累计阅读 48,350)
  2. 深入理解Javascript之执行上下文(Execution Context) (累计阅读 18,404)
  3. 从输入 URL 到页面加载完成的过程中都发生了什么事情? (累计阅读 15,933)
  4. 图片动态局部毛玻璃模糊效果的实现 (累计阅读 14,849)
  5. 天朝第二代身份证号码的验证机制 (累计阅读 14,762)
  6. HTML 5 的data-* 自定义属性 (累计阅读 14,349)
  7. 分享一个JQUERY颜色选择插件 (累计阅读 14,223)
  8. 什么是全栈工程师? (累计阅读 14,038)
  9. 快速排序(Quicksort)的Javascript实现 (累计阅读 11,735)
  10. 7 天打造前端性能监控系统 (累计阅读 11,187)