前端 本地缓存图片
localStorage和sessionStorage
localStorage:永久存储,只要不清除缓存,会一直存在
sessionStorage:临时存储,只在当前窗口有效,关闭当前窗口或新打开窗口无效
cookie:可以设置缓存时间
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <img id="aa" alt="A close up of an elephant" src="../image/01.png"> <img id="bb" alt="A close up of an elephant" src="../image/02.png"> </body> <script> var gsFiles = JSON.parse(sessionStorage.getItem("gsFiles")) || {}; var a = document.getElementById("aa"); var b = document.getElementById("bb"); gsFilesDate = gsFiles.date; date = new Date(); todaysDate = (date.getMonth() + 1).toString() + date.getDate().toString(); function imgLoad(el){ var imgCanvas = document.createElement("canvas"); imgContext = imgCanvas.getContext("2d"); // 确保canvas尺寸和图片一致 imgCanvas.width = el.width; imgCanvas.height = el.height; // 在canvas中绘制图片 imgContext.drawImage(el, 0, 0, el.width, el.height); // 将图片保存为Data URI if(el == a){ gsFiles.a = imgCanvas.toDataURL("bj.png"); }else{ gsFiles.b = imgCanvas.toDataURL("bj.png"); } //gsFiles.el = imgCanvas.toDataURL("bj.png"); gsFiles.date = todaysDate; // 将JSON保存到本地存储中 try { sessionStorage.setItem("gsFiles", JSON.stringify(gsFiles)); } catch (e) { console.log("Storage failed: " + e); } } // 检查数据,如果不存在或者数据过期,则创建一个本地存储 if (typeof gsFilesDate === "undefined" || gsFilesDate < todaysDate) { // 图片加载完成后执行 <!--image1--> a.addEventListener("load", function () { imgLoad(a) }, false); b.addEventListener("load", function () { imgLoad(b) }, false); // 设置图片 a.setAttribute("src", "../image/01.png"); b.setAttribute("src", "../image/02.png"); } else { // Use image from sessionStorage a.setAttribute("src", gsFiles.a); b.setAttribute("src", gsFiles.b); } console.log(document.cookie) </script> </html>
sessionStorage和localStorage用法相同
function setCookie(cname,cvalue,exdays){ var d = new Date(); d.setTime(d.getTime()+(exdays*24*60*60*1000)); var expires = "expires="+d.toGMTString(); document.cookie = cname+"="+cvalue+"; "+expires; } function getCookie(c_name){ if (document.cookie.length>0) { c_start=document.cookie.indexOf(c_name + "="); if (c_start!=-1) { c_start=c_start + c_name.length+1; c_end=document.cookie.indexOf(";",c_start); if (c_end==-1) c_end=document.cookie.length; return unescape(document.cookie.substring(c_start,c_end)) } } return "" } function checkCookie(){ var src=getCookie("src"), src1=getCookie("src1"); if (src==""){ setCookie("src","../image/02.png",30); setCookie("src1","../image/01.png",30); // alert(1) }else{ //setCookie("src",getCookie("username"),30); //alert(2) } document.getElementById("aa").src=getCookie("src"); document.getElementById("bb").src=getCookie("src1"); }