本地儲(chǔ)存

HTML5本地存儲(chǔ)Localstorage

文章目錄

什么是localstorage

前幾天在老項(xiàng)目中發(fā)現(xiàn)有對cookie的操作覺得很奇怪,咨詢下來是要緩存一些信息,以避免在URL上面?zhèn)鬟f參數(shù),但沒有考慮過cookie會(huì)帶來什么問題:

① cookie大小限制在4k左右,不適合存業(yè)務(wù)數(shù)據(jù)

② cookie每次隨HTTP事務(wù)一起發(fā)送,浪費(fèi)帶寬

我們是做移動(dòng)項(xiàng)目的,所以這里真實(shí)適合使用的技術(shù)是localstorage,localstorage可以說是對cookie的優(yōu)化,使用它可以方便在客戶端存儲(chǔ)數(shù)據(jù),并且不會(huì)隨著HTTP傳輸,但也不是沒有問題:

① localstorage大小限制在500萬字符左右,各個(gè)瀏覽器不一致

② localstorage在隱私模式下不可讀取

③ localstorage本質(zhì)是在讀寫文件,數(shù)據(jù)多的話會(huì)比較卡(firefox會(huì)一次性將數(shù)據(jù)導(dǎo)入內(nèi)存,想想就覺得嚇人?。?/p>

④ localstorage不能被爬蟲爬取,不要用它完全取代URL傳參

瑕不掩瑜,以上問題皆可避免,所以我們的關(guān)注點(diǎn)應(yīng)該放在如何使用localstorage上,并且是如何正確使用。

localstorage的使用

基礎(chǔ)知識(shí)

localstorage存儲(chǔ)對象分為兩種:

① sessionStrage: session即會(huì)話的意思,在這里的session是指用戶瀏覽某個(gè)網(wǎng)站時(shí),從進(jìn)入網(wǎng)站到關(guān)閉網(wǎng)站這個(gè)時(shí)間段,session對象的有效期就只有這么長。

② localStorage: 將數(shù)據(jù)保存在客戶端硬件設(shè)備上,不管它是什么,意思就是下次打開計(jì)算機(jī)時(shí)候數(shù)據(jù)還在。

兩者區(qū)別就是一個(gè)作為臨時(shí)保存,一個(gè)長期保存。

這里來一段簡單的代碼說明其基本使用:

? height: 100px;">

? 保存數(shù)據(jù)

? 讀取數(shù)據(jù)

? var msg = document.getElementById('msg'),

? ? ? ? ? ? text = document.getElementById('text'),

? ? ? ? ? ? type = document.getElementById('type');

? function save() {

? ? var str = text.value;

? ? var t = type.value;

? ? if (t == 'session') {

? ? ? sessionStorage.setItem('msg', str);

? ? } else {

? ? ? localStorage.setItem('msg', str);

? ? }

? }

? function load() {

? ? var t = type.value;

? ? if (t == 'session') {

? ? ? msg.innerHTML = sessionStorage.getItem('msg');

? ? } else {

? ? ? msg.innerHTML = localStorage.getItem('msg');

? ? }

? }

真實(shí)場景

實(shí)際工作中對localstorage的使用一般有以下需求:

① 緩存一般信息,如搜索頁的出發(fā)城市,達(dá)到城市,非實(shí)時(shí)定位信息

② 緩存城市列表數(shù)據(jù),這個(gè)數(shù)據(jù)往往比較大

③ 每條緩存信息需要可追蹤,比如服務(wù)器通知城市數(shù)據(jù)更新,這個(gè)時(shí)候在最近一次訪問的時(shí)候要自動(dòng)設(shè)置過期

④ 每條信息具有過期日期狀態(tài),在過期外時(shí)間需要由服務(wù)器拉取數(shù)據(jù)

⑤ ……

define([], function () {

? var Storage = _.inherit({

? ? //默認(rèn)屬性

? ? propertys: function () {

? ? ? //代理對象,默認(rèn)為localstorage

? ? ? this.sProxy = window.localStorage;

? ? ? //60 * 60 * 24 * 30 * 1000 ms ==30天

? ? ? this.defaultLifeTime = 2592000000;

? ? ? //本地緩存用以存放所有l(wèi)ocalstorage鍵值與過期日期的映射

? ? ? this.keyCache = 'SYSTEM_KEY_TIMEOUT_MAP';

? ? ? //當(dāng)緩存容量已滿,每次刪除的緩存數(shù)

? ? ? this.removeNum = 5;

? ? },

? ? assert: function () {

? ? ? if (this.sProxy === null) {

? ? ? ? throw 'not override sProxy property';

? ? ? }

? ? },

? ? initialize: function (opts) {

? ? ? this.propertys();

? ? ? this.assert();

? ? },

? ? /*

? ? 新增localstorage

? ? 數(shù)據(jù)格式包括唯一鍵值,json字符串,過期日期,存入日期

? ? sign 為格式化后的請求參數(shù),用于同一請求不同參數(shù)時(shí)候返回新數(shù)據(jù),比如列表為北京的城市,后切換為上海,會(huì)判斷tag不同而更新緩存數(shù)據(jù),tag相當(dāng)于簽名

? ? 每一鍵值只會(huì)緩存一條信息

? ? */

? ? set: function (key, value, timeout, sign) {

? ? ? var _d = new Date();

? ? ? //存入日期

? ? ? var indate = _d.getTime();

? ? ? //最終保存的數(shù)據(jù)

? ? ? var entity = null;

? ? ? if (!timeout) {

? ? ? ? _d.setTime(_d.getTime() + this.defaultLifeTime);

? ? ? ? timeout = _d.getTime();

? ? ? }

? ? ? //

? ? ? this.setKeyCache(key, timeout);

? ? ? entity = this.buildStorageObj(value, indate, timeout, sign);

? ? ? try {

? ? ? ? this.sProxy.setItem(key, JSON.stringify(entity));

? ? ? ? return true;

? ? ? } catch (e) {

? ? ? ? //localstorage寫滿時(shí),全清掉

? ? ? ? if (e.name == 'QuotaExceededError') {

? ? ? ? ? //? ? ? ? ? ? this.sProxy.clear();

? ? ? ? ? //localstorage寫滿時(shí),選擇離過期時(shí)間最近的數(shù)據(jù)刪除,這樣也會(huì)有些影響,但是感覺比全清除好些,如果緩存過多,此過程比較耗時(shí),100ms以內(nèi)

? ? ? ? ? if (!this.removeLastCache()) throw '本次數(shù)據(jù)存儲(chǔ)量過大';

? ? ? ? ? this.set(key, value, timeout, sign);

? ? ? ? }

? ? ? ? console && console.log(e);

? ? ? }

? ? ? return false;

? ? },

? ? //刪除過期緩存

? ? removeOverdueCache: function () {

? ? ? var tmpObj = null, i, len;

? ? ? var now = new Date().getTime();

? ? ? //取出鍵值對

? ? ? var cacheStr = this.sProxy.getItem(this.keyCache);

? ? ? var cacheMap = [];

? ? ? var newMap = [];

? ? ? if (!cacheStr) {

? ? ? ? return;

? ? ? }

? ? ? cacheMap = JSON.parse(cacheStr);

? ? ? for (i = 0, len = cacheMap.length; i < len; i++) {

? ? ? ? tmpObj = cacheMap[i];

? ? ? ? if (tmpObj.timeout < now) {

? ? ? ? ? this.sProxy.removeItem(tmpObj.key);

? ? ? ? } else {

? ? ? ? ? newMap.push(tmpObj);

? ? ? ? }

? ? ? }

? ? ? this.sProxy.setItem(this.keyCache, JSON.stringify(newMap));

? ? },

? ? removeLastCache: function () {

? ? ? var i, len;

? ? ? var num = this.removeNum || 5;

? ? ? //取出鍵值對

? ? ? var cacheStr = this.sProxy.getItem(this.keyCache);

? ? ? var cacheMap = [];

? ? ? var delMap = [];

? ? ? //說明本次存儲(chǔ)過大

? ? ? if (!cacheStr) return false;

? ? ? cacheMap.sort(function (a, b) {

? ? ? ? return a.timeout - b.timeout;

? ? ? });

? ? ? //刪除了哪些數(shù)據(jù)

? ? ? delMap = cacheMap.splice(0, num);

? ? ? for (i = 0, len = delMap.length; i < len; i++) {

? ? ? ? this.sProxy.removeItem(delMap[i].key);

? ? ? }

? ? ? this.sProxy.setItem(this.keyCache, JSON.stringify(cacheMap));

? ? ? return true;

? ? },

? ? setKeyCache: function (key, timeout) {

? ? ? if (!key || !timeout || timeout < new Date().getTime()) return;

? ? ? var i, len, tmpObj;

? ? ? //獲取當(dāng)前已經(jīng)緩存的鍵值字符串

? ? ? var oldstr = this.sProxy.getItem(this.keyCache);

? ? ? var oldMap = [];

? ? ? //當(dāng)前key是否已經(jīng)存在

? ? ? var flag = false;

? ? ? var obj = {};

? ? ? obj.key = key;

? ? ? obj.timeout = timeout;

? ? ? if (oldstr) {

? ? ? ? oldMap = JSON.parse(oldstr);

? ? ? ? if (!_.isArray(oldMap)) oldMap = [];

? ? ? }

? ? ? for (i = 0, len = oldMap.length; i < len; i++) {

? ? ? ? tmpObj = oldMap[i];

? ? ? ? if (tmpObj.key == key) {

? ? ? ? ? oldMap[i] = obj;

? ? ? ? ? flag = true;

? ? ? ? ? break;

? ? ? ? }

? ? ? }

? ? ? if (!flag) oldMap.push(obj);

? ? ? //最后將新數(shù)組放到緩存中

? ? ? this.sProxy.setItem(this.keyCache, JSON.stringify(oldMap));

? ? },

? ? buildStorageObj: function (value, indate, timeout, sign) {

? ? ? var obj = {

? ? ? ? value: value,

? ? ? ? timeout: timeout,

? ? ? ? sign: sign,

? ? ? ? indate: indate

? ? ? };

? ? ? return obj;

? ? },

? ? get: function (key, sign) {

? ? ? var result, now = new Date().getTime();

? ? ? try {

? ? ? ? result = this.sProxy.getItem(key);

? ? ? ? if (!result) return null;

? ? ? ? result = JSON.parse(result);

? ? ? ? //數(shù)據(jù)過期

? ? ? ? if (result.timeout < now) return null;

? ? ? ? //需要驗(yàn)證簽名

? ? ? ? if (sign) {

? ? ? ? ? if (sign === result.sign)

? ? ? ? ? ? return result.value;

? ? ? ? ? return null;

? ? ? ? } else {

? ? ? ? ? return result.value;

? ? ? ? }

? ? ? } catch (e) {

? ? ? ? console && console.log(e);

? ? ? }

? ? ? return null;

? ? },

? ? //獲取簽名

? ? getSign: function (key) {

? ? ? var result, sign = null;

? ? ? try {

? ? ? ? result = this.sProxy.getItem(key);

? ? ? ? if (result) {

? ? ? ? ? result = JSON.parse(result);

? ? ? ? ? sign = result && result.sign

? ? ? ? }

? ? ? } catch (e) {

? ? ? ? console && console.log(e);

? ? ? }

? ? ? return sign;

? ? },

? ? remove: function (key) {

? ? ? return this.sProxy.removeItem(key);

? ? },

? ? clear: function () {

? ? ? this.sProxy.clear();

? ? }

? });

? Storage.getInstance = function () {

? ? if (this.instance) {

? ? ? return this.instance;

? ? } else {

? ? ? return this.instance = new this();

? ? }

? };

? return Storage;

});

這段代碼包含了localstorage的基本操作,并且對以上問題做了處理,而真實(shí)的使用還要再抽象:

define(['AbstractStorage'], function (AbstractStorage) {

? var Store = _.inherit({

? ? //默認(rèn)屬性

? ? propertys: function () {

? ? ? //每個(gè)對象一定要具有存儲(chǔ)鍵,并且不能重復(fù)

? ? ? this.key = null;

? ? ? //默認(rèn)一條數(shù)據(jù)的生命周期,S為秒,M為分,D為天

? ? ? this.lifeTime = '30M';

? ? ? //默認(rèn)返回?cái)?shù)據(jù)

? ? ? //? ? ? this.defaultData = null;

? ? ? //代理對象,localstorage對象

? ? ? this.sProxy = new AbstractStorage();

? ? },

? ? setOption: function (options) {

? ? ? _.extend(this, options);

? ? },

? ? assert: function () {

? ? ? if (this.key === null) {

? ? ? ? throw 'not override key property';

? ? ? }

? ? ? if (this.sProxy === null) {

? ? ? ? throw 'not override sProxy property';

? ? ? }

? ? },

? ? initialize: function (opts) {

? ? ? this.propertys();

? ? ? this.setOption(opts);

? ? ? this.assert();

? ? },

? ? _getLifeTime: function () {

? ? ? var timeout = 0;

? ? ? var str = this.lifeTime;

? ? ? var unit = str.charAt(str.length - 1);

? ? ? var num = str.substring(0, str.length - 1);

? ? ? var Map = {

? ? ? ? D: 86400,

? ? ? ? H: 3600,

? ? ? ? M: 60,

? ? ? ? S: 1

? ? ? };

? ? ? if (typeof unit == 'string') {

? ? ? ? unit = unit.toUpperCase();

? ? ? }

? ? ? timeout = num;

? ? ? if (unit) timeout = Map[unit];

? ? ? //單位為毫秒

? ? ? return num * timeout * 1000 ;

? ? },

? ? //緩存數(shù)據(jù)

? ? set: function (value, sign) {

? ? ? //獲取過期時(shí)間

? ? ? var timeout = new Date();

? ? ? timeout.setTime(timeout.getTime() + this._getLifeTime());

? ? ? this.sProxy.set(this.key, value, timeout.getTime(), sign);

? ? },

? ? //設(shè)置單個(gè)屬性

? ? setAttr: function (name, value, sign) {

? ? ? var key, obj;

? ? ? if (_.isObject(name)) {

? ? ? ? for (key in name) {

? ? ? ? ? if (name.hasOwnProperty(key)) this.setAttr(k, name[k], value);

? ? ? ? }

? ? ? ? return;

? ? ? }

? ? ? if (!sign) sign = this.getSign();

? ? ? //獲取當(dāng)前對象

? ? ? obj = this.get(sign) || {};

? ? ? if (!obj) return;

? ? ? obj[name] = value;

? ? ? this.set(obj, sign);

? ? },

? ? getSign: function () {

? ? ? return this.sProxy.getSign(this.key);

? ? },

? ? remove: function () {

? ? ? this.sProxy.remove(this.key);

? ? },

? ? removeAttr: function (attrName) {

? ? ? var obj = this.get() || {};

? ? ? if (obj[attrName]) {

? ? ? ? delete obj[attrName];

? ? ? }

? ? ? this.set(obj);

? ? },

? ? get: function (sign) {

? ? ? var result = [], isEmpty = true, a;

? ? ? var obj = this.sProxy.get(this.key, sign);

? ? ? var type = typeof obj;

? ? ? var o = { 'string': true, 'number': true, 'boolean': true };

? ? ? if (o[type]) return obj;

? ? ? if (_.isArray(obj)) {

? ? ? ? for (var i = 0, len = obj.length; i < len; i++) {

? ? ? ? ? result[i] = obj[i];

? ? ? ? }

? ? ? } else if (_.isObject(obj)) {

? ? ? ? result = obj;

? ? ? }

? ? ? for (a in result) {

? ? ? ? isEmpty = false;

? ? ? ? break;

? ? ? }

? ? ? return !isEmpty ? result : null;

? ? },

? ? getAttr: function (attrName, tag) {

? ? ? var obj = this.get(t

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 單例模式 適用場景:可能會(huì)在場景中使用到對象,但只有一個(gè)實(shí)例,加載時(shí)并不主動(dòng)創(chuàng)建,需要時(shí)才創(chuàng)建 最常見的單例模式,...
    Obeing閱讀 2,311評(píng)論 1 10
  • 工廠模式類似于現(xiàn)實(shí)生活中的工廠可以產(chǎn)生大量相似的商品,去做同樣的事情,實(shí)現(xiàn)同樣的效果;這時(shí)候需要使用工廠模式。簡單...
    舟漁行舟閱讀 8,110評(píng)論 2 17
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,890評(píng)論 0 33
  • 郭相麟 一位加拿大女性多麗從少女時(shí)代堅(jiān)持寫作,無論生活發(fā)生什么狀況,都不改創(chuàng)作的初衷! 結(jié)婚生子,女兒夭折,第一段...
    郭相麟閱讀 200評(píng)論 0 0
  • 我認(rèn)為,自我認(rèn)知的過程是認(rèn)識(shí)自己和接受自己的過程。太多人看不清真正的自己,不愿接受那個(gè)看起來不太好的自己,一邊沉淪...
    江五圓閱讀 409評(píng)論 9 15

友情鏈接更多精彩內(nèi)容