Html5 localStorage 缓存

1.客户端页面临时存贮数据变化多段,cookie ,session, data-xxx , hidden input 这些司空见惯不废话,我们采用 localStorage

特点:1.数据不会删除,除非显示调用 clear. 2.数据量大 最大据有关测试为 2.6M左右

本次使用场景是:需要加载一部分数据,数据量比较大,更新不频繁。采用 localStorage 页面主要代码如下:

<script type="text/javascript">
    var curtime = new Date().getTime();
    var exp = 5;//5分钟后过期
    if (window.localStorage) {
        //支持
        alert("支持");
    } else {
        //不支持
        alert("不支持");
    }
    cacheInit();
    function cacheInit() {
        var exp = localStorage.getItem("exp");
        if (!exp) {
            localStorage.setItem("exp", curtime);//JSON.stringify({val:value,time:curtime}) 可设置缓存对象 eg: json对象等
        }
    }
    function setCache(key, val) {
        localStorage.setItem(key, val);
    }
    function getCache(key, delay) {
        delay = delay || exp;
        var exp_temp = localStorage.getItem("exp");
        var temp_dely = ((new Date().getTime() - exp_temp) / 60000);
        if (temp_dely > delay) {
            localStorage.clear();//过期后清除缓存
            cacheInit();
        } else {
            return localStorage.getItem(key);//获取存储的元素JSON.parse(localStorage.getItem(key))
        }
    }
    function Test() {
        alert("test");
        setCache("01", "001");
    }
    function TestGet(obj) {
        return getCache("01", obj);
    }
</script>

PS:适合客户端做一些数据的存贮。调用 插入 :setCache(key, val) 获取:getCache(key, 6) 即可。