localStorage/cookie 用法分析与简单封装
本地存儲(chǔ)是HTML5中提出來(lái)的概念,分localStorage和sessionStorage。通過(guò)本地存儲(chǔ),web應(yīng)用程序能夠在用戶(hù)瀏覽器中對(duì)數(shù)據(jù)進(jìn)行本地的存儲(chǔ)。與 cookie 不同,存儲(chǔ)限制要大得多(至少5MB),并且信息不會(huì)被傳輸?shù)椒?wù)器。
?
什么時(shí)候用本地存儲(chǔ)?
跨期:不同時(shí)間打開(kāi)頁(yè)面,比如這次登錄需要用到上次登錄時(shí)保存的數(shù)據(jù)。
跨頁(yè):在同一個(gè)瀏覽器打開(kāi)同域的多個(gè)標(biāo)簽頁(yè),它們之間需要互通數(shù)據(jù)。
?
選用哪種存儲(chǔ)方式?
最簡(jiǎn)單的數(shù)據(jù)保存方式就是在js里定義變量并賦值,這不屬于本地存儲(chǔ)的范疇,但大多數(shù)情況下這樣做就夠了。
cookie的適用場(chǎng)景:數(shù)據(jù)量小;數(shù)據(jù)需要隨http請(qǐng)求傳遞到服務(wù)端;存儲(chǔ)有具體時(shí)限的數(shù)據(jù);低版本瀏覽器,不支持localStorage和sessionStorage時(shí)。
localStorage的使用場(chǎng)景:數(shù)據(jù)大于4k;需要跨標(biāo)簽頁(yè)使用數(shù)據(jù);長(zhǎng)期存儲(chǔ)數(shù)據(jù);
sessionStorage的適用場(chǎng)景:數(shù)據(jù)只在本次會(huì)話(huà)有效;數(shù)據(jù)僅在當(dāng)前標(biāo)簽頁(yè)有效。sessionStorage對(duì)比直接js賦值變量的優(yōu)勢(shì),是可以在同頁(yè)面跨iframe使用。
瀏覽器自身會(huì)緩存img、js、css等數(shù)據(jù),localStorage也可以起到類(lèi)似作用。
?
整理本地存儲(chǔ)方法
基于localStorage制作一個(gè)本地存儲(chǔ)插件storage.js,針對(duì)只能存字符串、不能設(shè)置時(shí)限等進(jìn)行補(bǔ)充,設(shè)想:
- 在不支持localStorage時(shí)自動(dòng)使用cookie
- 類(lèi)型轉(zhuǎn)換,可存儲(chǔ)數(shù)字、布爾、對(duì)象等
- 可設(shè)置時(shí)限,超時(shí)就自我刪除
- 附帶整理cookie方法
用法展示:
/** setItem( key, value, time)* key: 鍵名,字符串* value:鍵值,可以是Stirng/Boolean/Number/Object等類(lèi)型* time: 超時(shí)時(shí)間,非必填,數(shù)字型(單位毫秒)。默認(rèn)長(zhǎng)期有效。**/storage.setItem("text", "this is string");storage.setItem("money", 1234);storage.setItem("person", {name: "Jone"}, 24*60*60*1000);// getItem 獲取值storage.getItem("money"); //返回?cái)?shù)字類(lèi)型的值1234// removeItem 刪除某數(shù)據(jù)storage.removeItem("money");// clear 清除所有數(shù)據(jù)storage.clear();// 類(lèi)似方法,操作cookie,只限于存儲(chǔ)字符串storage.setCookie("mycookie", "this is string", 60*60*24*30);storage.getCookie("mycookie");storage.removeCookie("mycookie");storage.clearCookie();storage.js :
(function(window) {var storage = {};// 是否支持localStorageif (!window.localStorage) {storage.support = false;} else {storage.support = true;}// time為超時(shí)時(shí)間(單位毫秒),非必填storage.setItem = function(key, value, time) {if (this.support) {if (typeof key != "string") {console.log("*STORAGE ERROR* key必須是字符串");return;}if (time) {if (typeof time != "number") {console.log("*STORAGE ERROR* time必須是數(shù)字");return;} else {time = parseInt(time) (new Date()).getTime();}} else {time = null;}var setValue = {value: JSON.stringify(value),time: time}localStorage.setItem(key, JSON.stringify(setValue));} else {storage.setCookie(key, value, time)}};// 不存在的值會(huì)返回nullstorage.getItem = function(key) {if (this.support) {var getValue = JSON.parse(localStorage.getItem(key));if (!getValue) {return null;}if (getValue.time && getValue.time < (new Date()).getTime()) {localStorage.removeItem(key);return null;} else {return JSON.parse(getValue.value)}} else {storage.getCookie(key)}};// 移除某個(gè)值storage.removeItem = function(key) {if (this.support) {localStorage.removeItem(key);} else {storage.removeCookie(key)}};// 清空存儲(chǔ)storage.clear = function() {if (this.support) {localStorage.clear();} else {storage.clearCookie();}};/**** cookie方法 ****/storage.setCookie = function(key, value, time) {if (typeof key != "string") {console.log("*STORAGE ERROR* key必須是字符串");return;} else {if (typeof time != "number") {// cookie默認(rèn)存365天time = 365 * 24 * 60 * 60 * 1000;}var d = new Date();d.setTime(d.getTime() time);document.cookie = key "=" value "; expires=" d.toGMTString();}};storage.getCookie = function(key) {var cookies = document.cookie.split(";")var cookieValue;for (var i = 0; i < cookies.length; i ) {if (key == cookies[i].split("=")[0]) {cookieValue = cookies[i].split("=")[1];break;}}return cookieValue;};storage.removeCookie = function(key) {document.cookie = key "=; expires=Thu, 01 Jan 1970 00:00:00 GMT";};storage.clearCookie = function() {var cookies = document.cookie.split(";")for (var i = 0; i < cookies.length; i ) {document.cookie = cookies[i].split("=")[0] "=; expires=Thu, 01 Jan 1970 00:00:00 GMT";}};window.storage = storage; })(window)
?
更多專(zhuān)業(yè)前端知識(shí),請(qǐng)上 【猿2048】www.mk2048.com
總結(jié)
以上是生活随笔為你收集整理的localStorage/cookie 用法分析与简单封装的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: call/apply以及this指向的理
- 下一篇: 原生js、jQuery实现选项卡功能