看着水了一天的羣,終於看到一段高質量的代碼了分享一下localStorage

_history : { //緩存
			isLocalStorage:window.localStorage?true:false,
			set : function(key,value){ //設置緩存
				if(this.isLocalStorage){
					window.localStorage.setItem(key,value);
				}else{
					var expireDays = 365; //失效時間
					var exDate=new Date();
					exDate.setTime(exDate.getTime()+expireDays*24*60*60*1000);
					document.cookie=key + "=" + escape(value)+";expires=" + exDate.toGMTString();
				}
			},
			read : function(key){ //讀取緩存
				if(this.isLocalStorage){
					return window.localStorage.getItem(key);
				}else{
					var arr,reg=new RegExp("(^| )"+key+"=([^;]*)(;|$)");
					if(arr=document.cookie.match(reg)){
						return unescape(arr[2]);
					}else{
						return null;
					}
				}
			},
			del : function(key){ //刪除緩存
				if(this.isLocalStorage){
					localStorage.removeItem(key);
				}else{
					var exDate = new Date();
					exDate.setTime(exDate.getTime() - 1);
					var read_val=this.read(key);
					if(read_val!=null) document.cookie= key + "="+read_val+";expires="+exDate.toGMTString();
				}
			}
		},

 

緩存下用戶操做 若是用戶點擊過」往返「我就緩存它 刷新或者下次打開就是往返javascript

localStorage+cookie
相關文章
相關標籤/搜索