search
HomeWeb Front-endH5 TutorialTutorial on using Localstorage in HTML5_html5 tutorial skills

What is localstorage

A few days ago, I found that the operation of cookies was very strange in an old project. After consulting, I wanted to cache some information to avoid passing parameters on the URL, but I did not consider the problems that cookies would cause:

 ① The cookie size is limited to about 4k, which is not suitable for storing business data
 ② Cookies are sent together with HTTP transactions each time, which wastes bandwidth

We are doing mobile projects, so the technology that is really suitable to use here is localstorage. Localstorage can be said to be an optimization of cookies. It can be used to store data on the client conveniently and will not be transmitted with HTTP, but it is not No problem:

 ① The size of localstorage is limited to about 5 million characters, and different browsers are inconsistent
 ② Localstorage cannot be read in privacy mode
 ③ The essence of localstorage is to read and write files. If there is a lot of data, it will be stuck (firefox will Importing data into memory at one time is scary when you think about it)
④ localstorage cannot be crawled by crawlers, do not use it to completely replace URL parameter passing

Flaws do not hide the advantages, the above problems can be avoided, so our focus should be on how to use localstorage, and how to use it correctly.
Usage of localstorage
Basic knowledge

There are two types of localstorage storage objects:

 ① sessionStrage: session means session. The session here refers to the time period from entering the website to closing the website when the user browses a website. The validity period of the session object is only so long.

 ② localStorage: Save the data on the client hardware device, no matter what it is, which means that the data will still be there when the computer is turned on next time.

The difference between the two is that one is for temporary storage and the other is for long-term storage.

Here is a simple code to illustrate its basic use:

XML/HTML CodeCopy content to clipboard
  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">sessionStorageoption>  
  7.   option value="local">localStorageoption>  
  8. select>  
  9. button onclick="save();">  
  10.   保存数据button>  
  11. button onclick="load();">  
  12.   读取数据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的使用一般有以下需求:

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

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

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

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

XML/HTML Code复制内容到剪贴板
  1. define([], function () {
  2. var Storage = _.inherit({
  3. //Default attributes
  4. properties: function () {
  5. //Proxy object, default is localstorage
  6. this.sProxy = window.localStorage;
  7. //60 * 60 * 24 * 30 * 1000 ms ==30 days
  8. this.defaultLifeTime = 2592000000;
  9. //Local cache is used to store the mapping between all localstorage key values ​​and expiration dates
  10. this.keyCache = 'SYSTEM_KEY_TIMEOUT_MAP';
  11. //When the cache capacity is full, the number of caches deleted each time
  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. Add localstorage
  25. Data format includes unique key value, json string, expiration date, deposit date
  26. sign is a formatted request parameter, used to return new data when the same request has different parameters. For example, if the list is the city of Beijing, and then switched to Shanghai, it will judge that the tag is different and update the cached data. The tag is equivalent to Signature
  27. Only one piece of information will be cached for each key value
  28. */
  29. set: function (key, value, timeout, sign) {
  30. var _d = new Date();
  31. //Deposit date
  32. var indate = _d.getTime();
  33. //Finally saved data
  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. //When localstorage is full, clear it all
  47. if (e.name == 'QuotaExceededError') {
  48. // this.sProxy.clear();
  49. //When localstorage is full, select the data closest to the expiration time to delete. This will also have some impact, but it feels better than clearing it all. If there are too many caches, this process will be more time-consuming, within 100ms
  50. if (!this.removeLastCache()) throw 'The amount of data stored this time is too large';
  51. this.set(key, value, timeout, sign);
  52.                                                               
  53. console && console.log(e);
  54. }
  55. return false;
  56. },
  57. //Delete expired cache
  58. removeOverdueCache: function () {
  59. var tmpObj = null, i, len;
  60. var now = new Date().getTime();
  61. //Get the key-value pair
  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. //Get the key-value pair
  83. var cacheStr = this.sProxy.getItem(this.keyCache);
  84. var cacheMap = [];
  85. var delMap = [];
  86. //Indicates that the storage is too large
  87. if (!cacheStr) return false;
  88. cacheMap.sort(function (a, b) {
  89. return a.timeout - b.timeout;
  90. });
  91. //What data was deleted
  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. //Get the currently cached key value string
  103. var oldstr = this.sProxy.getItem(this.keyCache);
  104. var oldMap = [];
  105. //Whether the current key already exists
  106. var flag = false;
  107. var obj = {};   
  108.       obj.key = key;   
  109.       obj.timeout = timeout;   
  110.   
  111.       if (oldstr) {   
  112.         oldMap = JSON.parse(oldstr);   
  113.         if (!_.isArray(oldMap)) oldMap = [];   
  114.       }   
  115.   
  116.       for (i = 0len = oldMap.length; i  len; i ) {   
  117.         tmpObj = oldMap[i];   
  118.         if (tmpObj.key == key) {   
  119.           oldMap[i] = obj;   
  120.           flag = true;   
  121.           break;   
  122.         }   
  123.       }   
  124.       if (!flag) oldMap.push(obj);   
  125.       //最后将新数组放到缓存中   
  126.       this.sProxy.setItem(this.keyCache, JSON.stringify(oldMap));   
  127.   
  128.     },   
  129.   
  130.     buildStorageObj: function (value, indate, timeout, sign) {   
  131.       var obj = {   
  132.         value: value,   
  133.         timeout: timeout,   
  134.         sign: sign,   
  135.         indate: indate   
  136.       };   
  137.       return obj;   
  138.     },
  139. get: function (key, sign) {
  140. var result, now = new Date().getTime();
  141. try {
  142. result = this.sProxy.getItem(key);
  143. if (!result) return null;
  144. result = JSON.parse(result);
  145. //Data expiration
  146. if (result.timeout now) return null;
  147. //Signature verification is required
  148. if (sign) {
  149. if (sign === result.sign)
  150. return result.value;
  151. return null;
  152. } else {
  153. return result.value;
  154.                                                               
  155. } catch (e) {
  156. console && console.log(e);
  157. }  
  158. return null;
  159. },
  160. //Get signature
  161. getSign: function (key) {
  162. var result,
  163. sign = null;
  164. try {
  165. result = this.sProxy.getItem(key);
  166. if (result) {
  167. result = JSON.parse(result);
  168. sign = result && result.sign
  169.                                                               
  170. } catch (e) {
  171. console && console.log(e);
  172. }  
  173.       return sign;   
  174.     },   
  175.   
  176.     remove: function (key) {   
  177.       return this.sProxy.removeItem(key);   
  178.     },   
  179.   
  180.     clear: function () {   
  181.       this.sProxy.clear();   
  182.     }   
  183.   });   
  184.   
  185.   Storage.getInstance = function () {   
  186.     if (this.instance) {   
  187.       return this.instance;   
  188.     } else {   
  189.       return this.instance = new this();   
  190.     }   
  191.   };   
  192.   
  193.   return Storage;   
  194.   
  195. });  

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

XML/HTML Code复制内容到剪贴板
  1. define(['AbstractStorage'], function (AbstractStorage) {
  2. var Store = _.inherit({
  3. //Default attributes
  4. properties: function () {
  5. //Each object must have a storage key and cannot be repeated
  6. this.key = null;
  7. //The default life cycle of a piece of data, S is seconds, M is minutes, D is days
  8. this.lifeTime = '30M';
  9. //Default return data
  10. // this.defaultData = null;
  11. //Proxy object, localstorage object
  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.   
  31.     _getLifeTime: function () {   
  32.       var timeout = 0;   
  33.       var str = this.lifeTime;   
  34.       var unit = str.charAt(str.length - 1);   
  35.       var num = str.substring(0, str.length - 1);   
  36.       var Map = {   
  37.         D: 86400,   
  38.         H: 3600,   
  39.         M: 60,   
  40.         S: 1   
  41.       };   
  42.       if (typeof unit == 'string') {   
  43.         unitunit = unit.toUpperCase();   
  44.       }   
  45.       timeout = num;   
  46.       if (unit) timeout = Map[unit];   
  47.   
  48.       //单位为毫秒   
  49.       return num * timeout * 1000 ;   
  50.     },   
  51.   
  52.     //缓存数据   
  53.     set: function (value, sign) {   
  54.       //获取过期时间   
  55.       var timeout = new Date();   
  56.       timeout.setTime(timeout.getTime()   this._getLifeTime());   
  57.       this.sProxy.set(this.key, value, timeout.getTime(), sign);   
  58.     },   
  59.   
  60.     //设置单个属性   
  61.     setAttr: function (name, value, sign) {   
  62.       var key, obj;   
  63.       if (_.isObject(name)) {   
  64.         for (key in name) {   
  65.           if (name.hasOwnProperty(key)) this.setAttr(k, name[k], value);   
  66.         }  
  67.         return;   
  68.       }   
  69.   
  70.       if (!sign) sign = this.getSign();   
  71.   
  72.       //获取当前对象   
  73.       obj = this.get(sign) || {};   
  74.       if (!obj) return;   
  75.       obj[name] = value;   
  76.       this.set(obj, sign);   
  77.   
  78.     },   
  79.   
  80.     getSign: function () {   
  81.       return this.sProxy.getSign(this.key);   
  82.     },   
  83.   
  84.     remove: function () {   
  85.       this.sProxy.remove(this.key);   
  86.     },   
  87.   
  88.     removeAttr: function (attrName) {   
  89.       var obj = this.get() || {};   
  90.       if (obj[attrName]) {   
  91.         delete obj[attrName];   
  92.       }   
  93.       this.set(obj);   
  94.     },   
  95.   
  96.     get: function (sign) {   
  97.       var result = [], isEmpty = true, a;   
  98.       var obj = this.sProxy.get(this.key, sign);   
  99.       var type = typeof obj;   
  100.       var o = { 'string': true, 'number': true, 'boolean': true };   
  101.       if (o[type]) return obj;   
  102.   
  103.       if (_.isArray(obj)) {   
  104.         for (var i = 0len = obj.length; i  len; i ) {   
  105.           result[i] = obj[i];   
  106.         }  
  107.       } else if (_.isObject(obj)) {   
  108.         result = obj;   
  109.       }   
  110.   
  111.       for (a in result) {   
  112.         isEmpty = false;   
  113.         break;   
  114.       }   
  115.       return !isEmpty ? result : null;   
  116.     },   
  117.   
  118.     getAttr: function (attrName, tag) {   
  119.       var obj = this.get(tag);   
  120.       var attrVal = null;   
  121.       if (obj) {   
  122.         attrVal = obj[attrName];   
  123.       }   
  124.       return attrVal;   
  125.     }   
  126.   
  127.   });   
  128.   
  129.   Store.getInstance = function () {   
  130.     if (this.instance) {   
  131.       return this.instance;   
  132.     } else {   
  133.       return this.instance = new this();   
  134.     }   
  135.   };   
  136.   
  137.   return Store;   
  138. });  

  我们真实使用的时候是使用store这个类操作localstorage,代码结束简单测试:
201579150514318.jpg (488×184)

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

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

 结语

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

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
H5: How It Enhances User Experience on the WebH5: How It Enhances User Experience on the WebApr 19, 2025 am 12:08 AM

H5 improves web user experience with multimedia support, offline storage and performance optimization. 1) Multimedia support: H5 and elements simplify development and improve user experience. 2) Offline storage: WebStorage and IndexedDB allow offline use to improve the experience. 3) Performance optimization: WebWorkers and elements optimize performance to reduce bandwidth consumption.

Deconstructing H5 Code: Tags, Elements, and AttributesDeconstructing H5 Code: Tags, Elements, and AttributesApr 18, 2025 am 12:06 AM

HTML5 code consists of tags, elements and attributes: 1. The tag defines the content type and is surrounded by angle brackets, such as. 2. Elements are composed of start tags, contents and end tags, such as contents. 3. Attributes define key-value pairs in the start tag, enhance functions, such as. These are the basic units for building web structure.

Understanding H5 Code: The Fundamentals of HTML5Understanding H5 Code: The Fundamentals of HTML5Apr 17, 2025 am 12:08 AM

HTML5 is a key technology for building modern web pages, providing many new elements and features. 1. HTML5 introduces semantic elements such as, , etc., which enhances web page structure and SEO. 2. Support multimedia elements and embed media without plug-ins. 3. Forms enhance new input types and verification properties, simplifying the verification process. 4. Offer offline and local storage functions to improve web page performance and user experience.

H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools