您的位置:首页 > Web前端

关于前端缓存的一个封装思路

2017-02-19 16:11 441 查看
function getCache (key) {
var cachedContentStr = window.localStorage.getItem(key);
console.log(cachedContentStr);
if (cachedContentStr ) {
var cachedContent = JSON.parse(cachedContentStr);
var cacheEndTime = cachedContent.cacheEndTime || 0;
if (cacheEndTime === 0) {
return cachedContent.realValue;
} else {
var currentDate = new Date().getTime();
if (currentDate <= cacheEndTime) {
return cachedContent.realValue;
}
}
}
return undefined;
};

/**
*
* @key 缓存的key
* @param value 对象字面量
* @timeOut 缓存的时间,单位是分钟
*/
function setCache(key, value, timeOut) {
timeOut = timeOut || 0;
value = value || {};
var timeOutms = 0;
var cachedContent = {};
if (timeOut > 0) {
var currentDate  = new Date().getTime();
timeOutms = timeOut * 60 * 1000;
var cacheEndTime = currentDate + timeOut;
cachedContent = {
realValue: value,
cacheEndTime: timeOutms
};
}else {
cachedContent = {
realValue: value,
cacheEndTime: timeOutms
};
}
window.localStorage.setItem(key, JSON.stringify(cachedContent));

};

function deleteCache (key) {
window.localStorage.removeItem(key);
};

/**
* 每次登陆的时候清空过期的localStorage内容,预防localStorage变得越来越大
*/
function deleteInvlidCache () {

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: