当前位置: 首页 > 工具软件 > JQuery Cache > 使用案例 >

jquery cache 缓存

全飞扬
2023-12-01

        做前端开发的朋友都用过javascript,用过js一定知道js缓存,说缓存其实不恰当,严格意义上这些缓存都是运行在内存中的,当你打开一个页面,该页面中的js就已经加入到了内存中,所以可以看到当打开网页多了浏览器占用的内容就越大,其实就是这个道理。

        在js中声明一个全局变量var map = new Array();那么该变量map其实就可以成为缓存,这就是一个简单的缓存例子,如果往这个array中多放些东西,就可以遍历里边的各个缓存内容了,只是这种写法效率比较低,没有jquery提供的cache效率高,至于jquery底层是怎么提高获取缓存效率的就不知道了,不过原理就是这样。

        下边说下jquery cache使用方法,先说下方法声明:

jQuery.extend({
    cache: {},
    uuid:
    expando           
});

jQuery.cache 空对象,用来缓存

jQuery.uuid 在最新1.9中删除了

jQuery.expando 每一个复制的jQuery独特标志,去掉了非数字,用在data时在HTMLElement或js对象上标志

方法的使用:

// 为HTMLElement提供缓存
$('#testCache').data("test", {first:16, last: "pizza!"});
$('#testCache span:first').text($("#testCache").data("test").first);
$('#testCache span:last').text($("#testCache").data("test").last);
 
// 为js对象提供缓存
var myObj = {};
$.data(myObj, 'name', 'jack');
console.log( $.data(myObj, 'name') );

如何存储:

1 如何在HTMLElement中存储缓存,数据最终存储在jQuery.cache中


<div id="testCache"></div>
<script>
  var el = document.getElementById('testCache');
  $.data(el, 'test', "value");
  console.log(el[jQuery.expando]); // 1
  console.log(jQuery.cache);    // {1: {data: {test:"value"}}};
</script>


2 在js对象中缓存,js直接用一个key来存储缓存对象

$.data(myObj, 'name', 'jack');

 类似资料: