欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

HTML5中Localstorage的使用教程

WEB開發(fā)者   發(fā)布時間:2015-07-09 15:08:12   作者:佚名   我要評論
這篇文章主要介紹了HTML5中Localstorage的使用教程,Localstorage被用于瀏覽器和系統(tǒng)交互的本地傳出,需要的朋友可以參考下

什么是localstorage

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

 ?、?cookie大小限制在4k左右,不適合存業(yè)務(wù)數(shù)據(jù)
 ?、?cookie每次隨HTTP事務(wù)一起發(fā)送,浪費帶寬

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

 ?、?localstorage大小限制在500萬字符左右,各個瀏覽器不一致
 ?、?localstorage在隱私模式下不可讀取
 ?、?localstorage本質(zhì)是在讀寫文件,數(shù)據(jù)多的話會比較卡(firefox會一次性將數(shù)據(jù)導(dǎo)入內(nèi)存,想想就覺得嚇人?。?br /> ?、?localstorage不能被爬蟲爬取,不要用它完全取代URL傳參

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

  localstorage存儲對象分為兩種:

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

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

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

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

XML/HTML Code復(fù)制內(nèi)容到剪貼板
  1. <div id="msg" style="margin: 10px 0; border: 1px solid black; padding: 10px; width: 300px;   
  2.   height: 100px;">  
  3. </div>  
  4. <input type="text" id="text" />  
  5. <select id="type">  
  6.   <option value="session">sessionStorage</option>  
  7.   <option value="local">localStorage</option>  
  8. </select>  
  9. <button onclick="save();">  
  10.   保存數(shù)據(jù)</button>  
  11. <button onclick="load();">  
  12.   讀取數(shù)據(jù)</button>  
  13. <script type="text/javascript">  
  14.   var msg = document.getElementById('msg'),   
  15.             text = document.getElementById('text'),   
  16.             type = document.getElementById('type');   
  17.   
  18.   function save() {   
  19.     var str = text.value;   
  20.     var t = type.value;   
  21.     if (t == 'session') {   
  22.       sessionStorage.setItem('msg', str);   
  23.     } else {   
  24.       localStorage.setItem('msg', str);   
  25.     }   
  26.   }   
  27.   
  28.   function load() {   
  29.     var t = type.value;   
  30.     if (t == 'session') {   
  31.       msg.innerHTML = sessionStorage.getItem('msg');   
  32.     } else {   
  33.       msg.innerHTML = localStorage.getItem('msg');   
  34.     }   
  35.   }   
  36. </script>  

 真實場景

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

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

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

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

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

XML/HTML Code復(fù)制內(nèi)容到剪貼板
  1. define([], function () {   
  2.   
  3.   var Storage = _.inherit({   
  4.     //默認(rèn)屬性   
  5.     propertys: function () {   
  6.   
  7.       //代理對象,默認(rèn)為localstorage   
  8.       this.sProxy = window.localStorage;   
  9.   
  10.       //60 * 60 * 24 * 30 * 1000 ms ==30天   
  11.       this.defaultLifeTime = 2592000000;   
  12.   
  13.       //本地緩存用以存放所有l(wèi)ocalstorage鍵值與過期日期的映射   
  14.       this.keyCache = 'SYSTEM_KEY_TIMEOUT_MAP';   
  15.   
  16.       //當(dāng)緩存容量已滿,每次刪除的緩存數(shù)   
  17.       this.removeNum = 5;   
  18.   
  19.     },   
  20.   
  21.     assert: function () {   
  22.       if (this.sProxy === null) {   
  23.         throw 'not override sProxy property';   
  24.       }   
  25.     },   
  26.   
  27.     initialize: function (opts) {   
  28.       this.propertys();   
  29.       this.assert();   
  30.     },   
  31.   
  32.     /*   
  33.     新增localstorage   
  34.     數(shù)據(jù)格式包括唯一鍵值,json字符串,過期日期,存入日期   
  35.     sign 為格式化后的請求參數(shù),用于同一請求不同參數(shù)時候返回新數(shù)據(jù),比如列表為北京的城市,后切換為上海,會判斷tag不同而更新緩存數(shù)據(jù),tag相當(dāng)于簽名   
  36.     每一鍵值只會緩存一條信息   
  37.     */   
  38.     set: function (key, value, timeout, sign) {   
  39.       var _d = new Date();   
  40.       //存入日期   
  41.       var indate = _d.getTime();   
  42.   
  43.       //最終保存的數(shù)據(jù)   
  44.       var entity = null;   
  45.   
  46.       if (!timeout) {   
  47.         _d.setTime(_d.getTime() + this.defaultLifeTime);   
  48.         timeout = _d.getTime();   
  49.       }   
  50.   
  51.       //   
  52.       this.setKeyCache(key, timeout);   
  53.       entity = this.buildStorageObj(value, indate, timeout, sign);   
  54.   
  55.       try {   
  56.         this.sProxy.setItem(key, JSON.stringify(entity));   
  57.         return true;   
  58.       } catch (e) {   
  59.         //localstorage寫滿時,全清掉   
  60.         if (e.name == 'QuotaExceededError') {   
  61.           //            this.sProxy.clear();   
  62.           //localstorage寫滿時,選擇離過期時間最近的數(shù)據(jù)刪除,這樣也會有些影響,但是感覺比全清除好些,如果緩存過多,此過程比較耗時,100ms以內(nèi)   
  63.           if (!this.removeLastCache()) throw '本次數(shù)據(jù)存儲量過大';   
  64.           this.set(key, value, timeout, sign);   
  65.         }   
  66.         console && console.log(e);   
  67.       }   
  68.       return false;   
  69.     },   
  70.   
  71.     //刪除過期緩存   
  72.     removeOverdueCache: function () {   
  73.       var tmpObj = null, i, len;   
  74.   
  75.       var now = new Date().getTime();   
  76.       //取出鍵值對   
  77.       var cacheStr = this.sProxy.getItem(this.keyCache);   
  78.       var cacheMap = [];   
  79.       var newMap = [];   
  80.       if (!cacheStr) {   
  81.         return;   
  82.       }   
  83.   
  84.       cacheMap = JSON.parse(cacheStr);   
  85.   
  86.       for (i = 0len = cacheMap.length; i < len; i++) {   
  87.         tmpObj = cacheMap[i];   
  88.         if (tmpObj.timeout < now) {   
  89.           this.sProxy.removeItem(tmpObj.key);   
  90.         } else {   
  91.           newMap.push(tmpObj);   
  92.         }   
  93.       }   
  94.       this.sProxy.setItem(this.keyCache, JSON.stringify(newMap));   
  95.   
  96.     },   
  97.   
  98.     removeLastCache: function () {   
  99.       var i, len;   
  100.       var num = this.removeNum || 5;   
  101.   
  102.       //取出鍵值對   
  103.       var cacheStr = this.sProxy.getItem(this.keyCache);   
  104.       var cacheMap = [];   
  105.       var delMap = [];   
  106.   
  107.       //說明本次存儲過大   
  108.       if (!cacheStr) return false;   
  109.   
  110.       cacheMap.sort(function (a, b) {   
  111.         return a.timeout - b.timeout;   
  112.       });   
  113.   
  114.       //刪除了哪些數(shù)據(jù)   
  115.       delMap = cacheMap.splice(0, num);   
  116.       for (i = 0len = delMap.length; i < len; i++) {   
  117.         this.sProxy.removeItem(delMap[i].key);   
  118.       }   
  119.   
  120.       this.sProxy.setItem(this.keyCache, JSON.stringify(cacheMap));   
  121.       return true;   
  122.     },   
  123.   
  124.     setKeyCache: function (key, timeout) {   
  125.       if (!key || !timeout || timeout < new Date().getTime()) return;   
  126.       var i, len, tmpObj;   
  127.   
  128.       //獲取當(dāng)前已經(jīng)緩存的鍵值字符串   
  129.       var oldstr = this.sProxy.getItem(this.keyCache);   
  130.       var oldMap = [];   
  131.       //當(dāng)前key是否已經(jīng)存在   
  132.       var flag = false;   
  133.       var obj = {};   
  134.       obj.key = key;   
  135.       obj.timeout = timeout;   
  136.   
  137.       if (oldstr) {   
  138.         oldMap = JSON.parse(oldstr);   
  139.         if (!_.isArray(oldMap)) oldMap = [];   
  140.       }   
  141.   
  142.       for (i = 0len = oldMap.length; i < len; i++) {   
  143.         tmpObj = oldMap[i];   
  144.         if (tmpObj.key == key) {   
  145.           oldMap[i] = obj;   
  146.           flag = true;   
  147.           break;   
  148.         }   
  149.       }   
  150.       if (!flag) oldMap.push(obj);   
  151.       //最后將新數(shù)組放到緩存中   
  152.       this.sProxy.setItem(this.keyCache, JSON.stringify(oldMap));   
  153.   
  154.     },   
  155.   
  156.     buildStorageObj: function (value, indate, timeout, sign) {   
  157.       var obj = {   
  158.         value: value,   
  159.         timeout: timeout,   
  160.         sign: sign,   
  161.         indate: indate   
  162.       };   
  163.       return obj;   
  164.     },   
  165.   
  166.     get: function (key, sign) {   
  167.       var result, now = new Date().getTime();   
  168.       try {   
  169.         result = this.sProxy.getItem(key);   
  170.         if (!result) return null;   
  171.         result = JSON.parse(result);   
  172.   
  173.         //數(shù)據(jù)過期   
  174.         if (result.timeout < now) return null;   
  175.   
  176.         //需要驗證簽名   
  177.         if (sign) {   
  178.           if (sign === result.sign)   
  179.             return result.value;   
  180.           return null;   
  181.         } else {   
  182.           return result.value;   
  183.         }   
  184.   
  185.       } catch (e) {   
  186.         console && console.log(e);   
  187.       }   
  188.       return null;   
  189.     },   
  190.   
  191.     //獲取簽名   
  192.     getSign: function (key) {   
  193.       var result, sign = null;   
  194.       try {   
  195.         result = this.sProxy.getItem(key);   
  196.         if (result) {   
  197.           result = JSON.parse(result);   
  198.           sign = result && result.sign   
  199.         }   
  200.       } catch (e) {   
  201.         console && console.log(e);   
  202.       }   
  203.       return sign;   
  204.     },   
  205.   
  206.     remove: function (key) {   
  207.       return this.sProxy.removeItem(key);   
  208.     },   
  209.   
  210.     clear: function () {   
  211.       this.sProxy.clear();   
  212.     }   
  213.   });   
  214.   
  215.   Storage.getInstance = function () {   
  216.     if (this.instance) {   
  217.       return this.instance;   
  218.     } else {   
  219.       return this.instance = new this();   
  220.     }   
  221.   };   
  222.   
  223.   return Storage;   
  224.   
  225. });  

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

XML/HTML Code復(fù)制內(nèi)容到剪貼板
  1. define(['AbstractStorage'], function (AbstractStorage) {   
  2.   
  3.   var Store = _.inherit({   
  4.     //默認(rèn)屬性   
  5.     propertys: function () {   
  6.   
  7.       //每個對象一定要具有存儲鍵,并且不能重復(fù)   
  8.       this.key = null;   
  9.   
  10.       //默認(rèn)一條數(shù)據(jù)的生命周期,S為秒,M為分,D為天   
  11.       this.lifeTime = '30M';   
  12.   
  13.       //默認(rèn)返回數(shù)據(jù)   
  14.       //      this.defaultData = null;   
  15.   
  16.       //代理對象,localstorage對象   
  17.       this.sProxy = new AbstractStorage();   
  18.   
  19.     },   
  20.   
  21.     setOption: function (options) {   
  22.       _.extend(this, options);   
  23.     },   
  24.   
  25.     assert: function () {   
  26.       if (this.key === null) {   
  27.         throw 'not override key property';   
  28.       }   
  29.       if (this.sProxy === null) {   
  30.         throw 'not override sProxy property';   
  31.       }   
  32.     },   
  33.   
  34.     initialize: function (opts) {   
  35.       this.propertys();   
  36.       this.setOption(opts);   
  37.       this.assert();   
  38.     },   
  39.   
  40.     _getLifeTime: function () {   
  41.       var timeout = 0;   
  42.       var str = this.lifeTime;   
  43.       var unit = str.charAt(str.length - 1);   
  44.       var num = str.substring(0, str.length - 1);   
  45.       var Map = {   
  46.         D: 86400,   
  47.         H: 3600,   
  48.         M: 60,   
  49.         S: 1   
  50.       };   
  51.       if (typeof unit == 'string') {   
  52.         unitunit = unit.toUpperCase();   
  53.       }   
  54.       timeout = num;   
  55.       if (unit) timeout = Map[unit];   
  56.   
  57.       //單位為毫秒   
  58.       return num * timeout * 1000 ;   
  59.     },   
  60.   
  61.     //緩存數(shù)據(jù)   
  62.     set: function (value, sign) {   
  63.       //獲取過期時間   
  64.       var timeout = new Date();   
  65.       timeout.setTime(timeout.getTime() + this._getLifeTime());   
  66.       this.sProxy.set(this.key, value, timeout.getTime(), sign);   
  67.     },   
  68.   
  69.     //設(shè)置單個屬性   
  70.     setAttr: function (name, value, sign) {   
  71.       var key, obj;   
  72.       if (_.isObject(name)) {   
  73.         for (key in name) {   
  74.           if (name.hasOwnProperty(key)) this.setAttr(k, name[k], value);   
  75.         }   
  76.         return;   
  77.       }   
  78.   
  79.       if (!sign) sign = this.getSign();   
  80.   
  81.       //獲取當(dāng)前對象   
  82.       obj = this.get(sign) || {};   
  83.       if (!obj) return;   
  84.       obj[name] = value;   
  85.       this.set(obj, sign);   
  86.   
  87.     },   
  88.   
  89.     getSign: function () {   
  90.       return this.sProxy.getSign(this.key);   
  91.     },   
  92.   
  93.     remove: function () {   
  94.       this.sProxy.remove(this.key);   
  95.     },   
  96.   
  97.     removeAttr: function (attrName) {   
  98.       var obj = this.get() || {};   
  99.       if (obj[attrName]) {   
  100.         delete obj[attrName];   
  101.       }   
  102.       this.set(obj);   
  103.     },   
  104.   
  105.     get: function (sign) {   
  106.       var result = [], isEmpty = true, a;   
  107.       var obj = this.sProxy.get(this.key, sign);   
  108.       var type = typeof obj;   
  109.       var o = { 'string': true, 'number': true, 'boolean': true };   
  110.       if (o[type]) return obj;   
  111.   
  112.       if (_.isArray(obj)) {   
  113.         for (var i = 0len = obj.length; i < len; i++) {   
  114.           result[i] = obj[i];   
  115.         }   
  116.       } else if (_.isObject(obj)) {   
  117.         result = obj;   
  118.       }   
  119.   
  120.       for (a in result) {   
  121.         isEmpty = false;   
  122.         break;   
  123.       }   
  124.       return !isEmpty ? result : null;   
  125.     },   
  126.   
  127.     getAttr: function (attrName, tag) {   
  128.       var obj = this.get(tag);   
  129.       var attrVal = null;   
  130.       if (obj) {   
  131.         attrVal = obj[attrName];   
  132.       }   
  133.       return attrVal;   
  134.     }   
  135.   
  136.   });   
  137.   
  138.   Store.getInstance = function () {   
  139.     if (this.instance) {   
  140.       return this.instance;   
  141.     } else {   
  142.       return this.instance = new this();   
  143.     }   
  144.   };   
  145.   
  146.   return Store;   
  147. });  

  我們真實使用的時候是使用store這個類操作localstorage,代碼結(jié)束簡單測試:
201579150514318.jpg (488×184)

 存儲完成,以后都不會走請求,于是今天的代碼基本結(jié)束 ,最后在android Hybrid中有一后退按鈕,此按鈕一旦按下會回到上一個頁面,這個時候里面的localstorage可能會讀取失效!一個簡單不靠譜的解決方案是在webapp中加入:

XML/HTML Code復(fù)制內(nèi)容到剪貼板
  1. window.onunload = function () { };//適合單頁應(yīng)用,不要問我為什么,我也不知道  

 結(jié)語

  localstorage是移動開發(fā)必不可少的技術(shù)點,需要深入了解,具體業(yè)務(wù)代碼后續(xù)會放到git上,有興趣的朋友可以去了解

相關(guān)文章

  • HTML5 LocalStorage 本地存儲詳細(xì)概括(多圖)

    這篇文章主要介紹了HTML5 LocalStorage 本地存儲,給標(biāo)簽元素添加屬性和瀏覽器兼容性都做了詳細(xì)概括,具體操作步驟大家可查看下文的詳細(xì)講解,感興趣的小伙伴們可以參考一
    2017-08-18
  • html5 localStorage本地存儲_動力節(jié)點Java學(xué)院整理

    localStorage 即本地存儲,可用于長久保存整個網(wǎng)站的數(shù)據(jù),保存的數(shù)據(jù)沒有過期時間,直到手動去除
    2017-07-06
  • localstorage和sessionstorage使用記錄(推薦)

    通過閱讀各路大神對web存儲locastorage和sessionstorage的用法解析,深有感觸,下面小編把localstorage和sessionstorage使用記錄分享到腳本之家平臺,供大家參考
    2017-05-23
  • 詳解HTML5 LocalStorage 本地存儲

    本篇文章主要介紹了HTML5 LocalStorage 本地存儲 ,HTML5 storage提供了一種方式讓網(wǎng)站能夠把信息存儲到你本地的計算機(jī)上,并再以后需要的時候進(jìn)行獲取。有興趣的可以了解
    2016-12-23
  • html5本地存儲 localStorage操作使用詳解

    這篇文章主要介紹了html5本地存儲 localStorage操作使用詳解的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2016-09-20
  • HTML5 本地存儲 LocalStorage詳解

    下面小編就為大家?guī)硪黄狧TML5 本地存儲 LocalStorage詳解。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-06-24
  • 解析HTML5中的新功能本地存儲localStorage

    這篇文章主要介紹了HTML5中的新功能本地存儲localStorage,介紹了localStorage的本地存儲位置和幾個常用方法,需要的朋友可以參考下
    2016-03-01
  • localStorage的過期時間設(shè)置的方法詳解

    這篇文章主要介紹了localStorage的過期時間設(shè)置的方法詳解的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨
    2018-11-26

最新評論