基于localStorage开发的前端缓存jquery插件,jquery.cache.js

什么是localStorage?

在HTML5中,新加入了一个localStorage特性,这个特性主要是用来作为本地存储来使用的,解决了cookie存储空间不足的问题(cookie中每条cookie的存储空间为4k),localStorage中一般浏览器支持的是5M大小,这个在不同的浏览器中localStorage会有所不同

localStorage的优势

1、localStorage拓展了cookie的4K限制

2、localStorage会可以将第一次请求的数据直接存储到本地,这个相当于一个5M大小的针对于前端页面的数据库,相比于cookie可以节约带宽,但是这个却是只有在高版本的浏览器中才支持的

localStorage的局限

1、浏览器的大小不统一,并且在IE8以上的IE版本才支持localStorage这个属性

2、目前所有的浏览器中都会把localStorage的值类型限定为string类型,这个在对我们日常比较常见的JSON对象类型需要一些转换

3、localStorage在浏览器的隐私模式下面是不可读取的

4、localStorage本质上是对字符串的读取,如果存储内容多的话会消耗内存空间,会导致页面变卡

5、localStorage不能被爬虫抓取到

localStorage与sessionStorage的唯一一点区别就是localStorage属于永久性存储,而sessionStorage属于当会话结束的时候,sessionStorage中的键值对会被清空

 

jquery.cache.js 主要代码如下:

;(function(window, undefined) {
	var config = {
		expire : 60, //缓存数据默认十分钟失效
		debug : false
	};

	function setCache(key, obj) {
		var data = JSON.stringify(obj);
		var time = new Date().getTime();
		var jsonData = { "data" : obj, "cacheTime" : time };
		if (config.debug) console.log("设置缓存数据:" + data);
		return localStorage.setItem(key, JSON.stringify(jsonData));
	}

	function getCache(key) {
		if (!key) {
			if (config.debug)
				console.log("key为空,key=【" + key + "】");
			return "";
		}
		var jsonData = JSON.parse(localStorage.getItem(key));
		if (!jsonData) {
			if (config.debug) console.log("【" + key + "】缓存的数据不存在");
			return "";
		}
		var nowDate = new Date().getTime();
		var cacheTime = new Date(jsonData.cacheTime).getTime();
		if (apartMinutes(cacheTime, nowDate) > config.expire) {
			if (config.debug) console.log("超过" + config.expire + "分钟 ,【" + key + "】缓存失效!");
			return "";
		}
		if (config.debug) console.log("【" + key + "】获取到的缓存数据:" + jsonData.data);
		return jsonData.data;
	}

	function apartMinutes(date1, date2) {
		var date3 = date2 - date1;
		var minutes = Math.floor(date3 / (60 * 1000));
		if (config.debug) console.log("数据已缓存时间:" + minutes + "分钟");
		return minutes;
	}

	var cache = {
		getCache : getCache,
		setCache : setCache,
		configCache : function(obj) { $.extend(config, obj); }
	};
	window.jQuery && ($.extend(window.jQuery, cache));
})(window);

功能介绍:

主要用于前端页面数据缓存,提高页面的响应能力,快速获取常用数据;

可以将要缓存的数据转换为json字符串存储:

缓存设置的有效时间默认为十分钟,可以通过配置进行修改缓存时间;

也可以通过配置是否输出日志。

使用方法:

1.设置缓存

假设要缓存的数据为一个数组对象:

var datas=[{"id":"1","name":"andy"},{"id":"2","name":"lili"},{"id":"1","name":"lucy"}];

则可以设置

$.setCache("users",datas);

2.获取数据

var datas=$.getCache("users");

      $.each(datas, function (index, data) {
          var id=data.id;
          var name = data.name;

          console.log(index+":id="+id+",name="+name);

      });

3,配置缓存时间和日志输出

$.configCache({"expire": 20,"debug  : true});

操作结果如下:

基于localStorage开发的前端缓存jquery插件,jquery.cache.js
基于localStorage开发的前端缓存jquery插件,jquery.cache.js

 

本文:基于localStorage开发的前端缓存jquery插件,jquery.cache.js

Loading

Add a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.