
纯前端如何做缓存,下面web建站小编给大家简单介绍一下三种不同的方法,它们分别是cookie、localStorage和sesstionStorage。
1、利用cookie方法实现缓存
//设置缓存
function setCookie(cname,cvalue,exdays){
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
// 得到GMT时间
var expires = "expires="+d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
//获取缓存
function getCookie(cname){
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name)==0) { return c.substring(name.length,c.length); }
}
return "";
}
//检查缓存
function checkCookie(){
var user=getCookie("username");
if (user!=""){
console.log(111)
}
else {
if (user!="" && user!=null){
setCookie("username",user,30);
}
}
}
2、利用localStorage方法实现缓存
localStorage.setItem(key, value) //添加缓存 localStorage.getItem(key) //获取缓存 localStorage.removeItem(key) 删除缓存 localStorage.clear() //清空所有缓存 localStorage.length //获取缓存长度
3、利用sesstionStorage方法实现缓存
sessionStorage.setItem(key, value) //添加缓存 sessionStorage.getItem(key) //获取缓存 sessionStorage.removeItem(key) 删除缓存 sessionStorage.clear() //清空所有缓存
标签: cookie, localStorage, sesstionStorage
上面是“纯前端有哪些方法可以实现缓存”的全面内容,想了解更多关于 js 内容,请继续关注web建站教程。
当前网址:https://m.ipkd.cn/webs_3680.html
声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

帝国CMS如何关闭文章后面的评论功能
DeepSeek网页版入口,附iOS和Android下载地址
CodeFuse:一款由蚂蚁自研的AI智能研发助手