最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

HTML5中Localstorage的使用教程_html5教程技巧

来源:动视网 责编:小采 时间:2020-11-27 15:19:36
文档

HTML5中Localstorage的使用教程_html5教程技巧

HTML5中Localstorage的使用教程_html5教程技巧:什么是localstorage 前几天在老项目中发现有对cookie的操作觉得很奇怪,咨询下来是要缓存一些信息,以避免在URL上面传递参数,但没有考虑过cookie会带来什么问题: ① cookie大小限制在4k左右,不适合存业务数据 ② cookie每次随HTTP事务一起发
推荐度:
导读HTML5中Localstorage的使用教程_html5教程技巧:什么是localstorage 前几天在老项目中发现有对cookie的操作觉得很奇怪,咨询下来是要缓存一些信息,以避免在URL上面传递参数,但没有考虑过cookie会带来什么问题: ① cookie大小限制在4k左右,不适合存业务数据 ② cookie每次随HTTP事务一起发
 什么是localstorage

  前几天在老项目中发现有对cookie的操作觉得很奇怪,咨询下来是要缓存一些信息,以避免在URL上面传递参数,但没有考虑过cookie会带来什么问题:

  ① cookie大小限制在4k左右,不适合存业务数据
  ② cookie每次随HTTP事务一起发送,浪费带宽

  我们是做移动项目的,所以这里真实适合使用的技术是localstorage,localstorage可以说是对cookie的优化,使用它可以方便在客户端存储数据,并且不会随着HTTP传输,但也不是没有问题:

  ① localstorage大小限制在500万字符左右,各个浏览器不一致
  ② localstorage在隐私模式下不可读取
  ③ localstorage本质是在读写文件,数据多的话会比较卡(firefox会一次性将数据导入内存,想想就觉得吓人啊)
  ④ localstorage不能被爬虫爬取,不要用它完全取代URL传参

  瑕不掩瑜,以上问题皆可避免,所以我们的关注点应该放在如何使用localstorage上,并且是如何正确使用。
localstorage的使用
  基础知识

  localstorage存储对象分为两种:

  ① sessionStrage: session即会话的意思,在这里的session是指用户浏览某个网站时,从进入网站到关闭网站这个时间段,session对象的有效期就只有这么长。

  ② localStorage: 将数据保存在客户端硬件设备上,不管它是什么,意思就是下次打开计算机时候数据还在。

  两者区别就是一个作为临时保存,一个长期保存。

  这里来一段简单的代码说明其基本使用:

XML/HTML Code复制内容到剪贴板

  • 保存数据
  • 读取数据
  •  真实场景

      实际工作中对localstorage的使用一般有以下需求:

      ① 缓存一般信息,如搜索页的出发城市,达到城市,非实时定位信息

      ② 缓存城市列表数据,这个数据往往比较大

      ③ 每条缓存信息需要可追踪,比如服务器通知城市数据更新,这个时候在最近一次访问的时候要自动设置过期

      ④ 每条信息具有过期日期状态,在过期外时间需要由服务器拉取数据

    XML/HTML Code复制内容到剪贴板
    
    
    1. define([], function () {
    2. var Storage = _.inherit({
    3. //默认属性
    4. propertys: function () {
    5. //代理对象,默认为localstorage
    6. this.sProxy = window.localStorage;
    7. //60 * 60 * 24 * 30 * 1000 ms ==30天
    8. this.defaultLifeTime = 2592000000;
    9. //本地缓存用以存放所有localstorage键值与过期日期的映射
    10. this.keyCache = 'SYSTEM_KEY_TIMEOUT_MAP';
    11. //当缓存容量已满,每次删除的缓存数
    12. this.removeNum = 5;
    13. },
    14. assert: function () {
    15. if (this.sProxy === null) {
    16. throw 'not override sProxy property';
    17. }
    18. },
    19. initialize: function (opts) {
    20. this.propertys();
    21. this.assert();
    22. },
    23. /*
    24. 新增localstorage
    25. 数据格式包括唯一键值,json字符串,过期日期,存入日期
    26. sign 为格式化后的请求参数,用于同一请求不同参数时候返回新数据,比如列表为北京的城市,后切换为上海,会判断tag不同而更新缓存数据,tag相当于签名
    27. 每一键值只会缓存一条信息
    28. */
    29. set: function (key, value, timeout, sign) {
    30. var _d = new Date();
    31. //存入日期
    32. var indate = _d.getTime();
    33. //最终保存的数据
    34. var entity = null;
    35. if (!timeout) {
    36. _d.setTime(_d.getTime() + this.defaultLifeTime);
    37. timeout = _d.getTime();
    38. }
    39. //
    40. this.setKeyCache(key, timeout);
    41. entity = this.buildStorageObj(value, indate, timeout, sign);
    42. try {
    43. this.sProxy.setItem(key, JSON.stringify(entity));
    44. return true;
    45. } catch (e) {
    46. //localstorage写满时,全清掉
    47. if (e.name == 'QuotaExceededError') {
    48. // this.sProxy.clear();
    49. //localstorage写满时,选择离过期时间最近的数据删除,这样也会有些影响,但是感觉比全清除好些,如果缓存过多,此过程比较耗时,100ms以内
    50. if (!this.removeLastCache()) throw '本次数据存储量过大';
    51. this.set(key, value, timeout, sign);
    52. }
    53. console && console.log(e);
    54. }
    55. return false;
    56. },
    57. //删除过期缓存
    58. removeOverdueCache: function () {
    59. var tmpObj = null, i, len;
    60. var now = new Date().getTime();
    61. //取出键值对
    62. var cacheStr = this.sProxy.getItem(this.keyCache);
    63. var cacheMap = [];
    64. var newMap = [];
    65. if (!cacheStr) {
    66. return;
    67. }
    68. cacheMap = JSON.parse(cacheStr);
    69. for (i = 0, len = cacheMap.length; i < len; i++) {
    70. tmpObj = cacheMap[i];
    71. if (tmpObj.timeout < now) {
    72. this.sProxy.removeItem(tmpObj.key);
    73. } else {
    74. newMap.push(tmpObj);
    75. }
    76. }
    77. this.sProxy.setItem(this.keyCache, JSON.stringify(newMap));
    78. },
    79. removeLastCache: function () {
    80. var i, len;
    81. var num = this.removeNum || 5;
    82. //取出键值对
    83. var cacheStr = this.sProxy.getItem(this.keyCache);
    84. var cacheMap = [];
    85. var delMap = [];
    86. //说明本次存储过大
    87. if (!cacheStr) return false;
    88. cacheMap.sort(function (a, b) {
    89. return a.timeout - b.timeout;
    90. });
    91. //删除了哪些数据
    92. delMap = cacheMap.splice(0, num);
    93. for (i = 0, len = delMap.length; i < len; i++) {
    94. this.sProxy.removeItem(delMap[i].key);
    95. }
    96. this.sProxy.setItem(this.keyCache, JSON.stringify(cacheMap));
    97. return true;
    98. },
    99. setKeyCache: function (key, timeout) {
    100. if (!key || !timeout || timeout < new Date().getTime()) return;
    101. var i, len, tmpObj;
    102. //获取当前已经缓存的键值字符串
    103. var oldstr = this.sProxy.getItem(this.keyCache);
    104. var oldMap = [];
    105. //当前key是否已经存在
    106. var flag = false;
    107. var obj = {};
    108. obj.key = key;
    109. obj.timeout = timeout;
    110. if (oldstr) {
    111. oldMap = JSON.parse(oldstr);
    112. if (!_.isArray(oldMap)) oldMap = [];
    113. }
    114. for (i = 0, len = oldMap.length; i < len; i++) {
    115. tmpObj = oldMap[i];
    116. if (tmpObj.key == key) {
    117. oldMap[i] = obj;
    118. flag = true;
    119. break;
    120. }
    121. }
    122. if (!flag) oldMap.push(obj);
    123. //最后将新数组放到缓存中
    124. this.sProxy.setItem(this.keyCache, JSON.stringify(oldMap));
    125. },
    126. buildStorageObj: function (value, indate, timeout, sign) {
    127. var obj = {
    128. value: value,
    129. timeout: timeout,
    130. sign: sign,
    131. indate: indate
    132. };
    133. return obj;
    134. },
    135. get: function (key, sign) {
    136. var result, now = new Date().getTime();
    137. try {
    138. result = this.sProxy.getItem(key);
    139. if (!result) return null;
    140. result = JSON.parse(result);
    141. //数据过期
    142. if (result.timeout < now) return null;
    143. //需要验证签名
    144. if (sign) {
    145. if (sign === result.sign)
    146. return result.value;
    147. return null;
    148. } else {
    149. return result.value;
    150. }
    151. } catch (e) {
    152. console && console.log(e);
    153. }
    154. return null;
    155. },
    156. //获取签名
    157. getSign: function (key) {
    158. var result, sign = null;
    159. try {
    160. result = this.sProxy.getItem(key);
    161. if (result) {
    162. result = JSON.parse(result);
    163. sign = result && result.sign
    164. }
    165. } catch (e) {
    166. console && console.log(e);
    167. }
    168. return sign;
    169. },
    170. remove: function (key) {
    171. return this.sProxy.removeItem(key);
    172. },
    173. clear: function () {
    174. this.sProxy.clear();
    175. }
    176. });
    177. Storage.getInstance = function () {
    178. if (this.instance) {
    179. return this.instance;
    180. } else {
    181. return this.instance = new this();
    182. }
    183. };
    184. return Storage;
    185. });

    这段代码包含了localstorage的基本操作,并且对以上问题做了处理,而真实的使用还要再抽象:

    XML/HTML Code复制内容到剪贴板
    
    
    1. define(['AbstractStorage'], function (AbstractStorage) {
    2. var Store = _.inherit({
    3. //默认属性
    4. propertys: function () {
    5. //每个对象一定要具有存储键,并且不能重复
    6. this.key = null;
    7. //默认一条数据的生命周期,S为秒,M为分,D为天
    8. this.lifeTime = '30M';
    9. //默认返回数据
    10. // this.defaultData = null;
    11. //代理对象,localstorage对象
    12. this.sProxy = new AbstractStorage();
    13. },
    14. setOption: function (options) {
    15. _.extend(this, options);
    16. },
    17. assert: function () {
    18. if (this.key === null) {
    19. throw 'not override key property';
    20. }
    21. if (this.sProxy === null) {
    22. throw 'not override sProxy property';
    23. }
    24. },
    25. initialize: function (opts) {
    26. this.propertys();
    27. this.setOption(opts);
    28. this.assert();
    29. },
    30. _getLifeTime: function () {
    31. var timeout = 0;
    32. var str = this.lifeTime;
    33. var unit = str.charAt(str.length - 1);
    34. var num = str.substring(0, str.length - 1);
    35. var Map = {
    36. D: 86400,
    37. H: 3600,
    38. M: 60,
    39. S: 1
    40. };
    41. if (typeof unit == 'string') {
    42. unitunit = unit.toUpperCase();
    43. }
    44. timeout = num;
    45. if (unit) timeout = Map[unit];
    46. //单位为毫秒
    47. return num * timeout * 1000 ;
    48. },
    49. //缓存数据
    50. set: function (value, sign) {
    51. //获取过期时间
    52. var timeout = new Date();
    53. timeout.setTime(timeout.getTime() + this._getLifeTime());
    54. this.sProxy.set(this.key, value, timeout.getTime(), sign);
    55. },
    56. //设置单个属性
    57. setAttr: function (name, value, sign) {
    58. var key, obj;
    59. if (_.isObject(name)) {
    60. for (key in name) {
    61. if (name.hasOwnProperty(key)) this.setAttr(k, name[k], value);
    62. }
    63. return;
    64. }
    65. if (!sign) sign = this.getSign();
    66. //获取当前对象
    67. obj = this.get(sign) || {};
    68. if (!obj) return;
    69. obj[name] = value;
    70. this.set(obj, sign);
    71. },
    72. getSign: function () {
    73. return this.sProxy.getSign(this.key);
    74. },
    75. remove: function () {
    76. this.sProxy.remove(this.key);
    77. },
    78. removeAttr: function (attrName) {
    79. var obj = this.get() || {};
    80. if (obj[attrName]) {
    81. delete obj[attrName];
    82. }
    83. this.set(obj);
    84. },
    85. get: function (sign) {
    86. var result = [], isEmpty = true, a;
    87. var obj = this.sProxy.get(this.key, sign);
    88. var type = typeof obj;
    89. var o = { 'string': true, 'number': true, 'boolean': true };
    90. if (o[type]) return obj;
    91. if (_.isArray(obj)) {
    92. for (var i = 0, len = obj.length; i < len; i++) {
    93. result[i] = obj[i];
    94. }
    95. } else if (_.isObject(obj)) {
    96. result = obj;
    97. }
    98. for (a in result) {
    99. isEmpty = false;
    100. break;
    101. }
    102. return !isEmpty ? result : null;
    103. },
    104. getAttr: function (attrName, tag) {
    105. var obj = this.get(tag);
    106. var attrVal = null;
    107. if (obj) {
    108. attrVal = obj[attrName];
    109. }
    110. return attrVal;
    111. }
    112. });
    113. Store.getInstance = function () {
    114. if (this.instance) {
    115. return this.instance;
    116. } else {
    117. return this.instance = new this();
    118. }
    119. };
    120. return Store;
    121. });

      我们真实使用的时候是使用store这个类操作localstorage,代码结束简单测试:

     存储完成,以后都不会走请求,于是今天的代码基本结束 ,最后在android Hybrid中有一后退按钮,此按钮一旦按下会回到上一个页面,这个时候里面的localstorage可能会读取失效!一个简单不靠谱的解决方案是在webapp中加入:

    XML/HTML Code复制内容到剪贴板
    
    
    1. window.onunload = function () { };//适合单页应用,不要问我为什么,我也不知道

     结语

      localstorage是移动开发必不可少的技术点,需要深入了解,具体业务代码后续会放到git上,有兴趣的朋友可以去了解

    文档

    HTML5中Localstorage的使用教程_html5教程技巧

    HTML5中Localstorage的使用教程_html5教程技巧:什么是localstorage 前几天在老项目中发现有对cookie的操作觉得很奇怪,咨询下来是要缓存一些信息,以避免在URL上面传递参数,但没有考虑过cookie会带来什么问题: ① cookie大小限制在4k左右,不适合存业务数据 ② cookie每次随HTTP事务一起发
    推荐度:
    标签: 使用 html5 html中
    • 热门焦点

    最新推荐

    猜你喜欢

    热门推荐

    专题
    Top