Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Localstorage in HTML5

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to use Localstorage in HTML5". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use Localstorage in HTML5.

What is localstorage?

A few days ago, I found it strange to operate on cookie in an old project. I consulted to cache some information to avoid passing parameters on URL, but did not consider what problems cookie would bring:

The size of ① cookie is limited to about 4k and is not suitable for storing business data.

② cookie is sent with HTTP transactions every time, wasting bandwidth

We are working on mobile projects, so the technology that is really suitable for use here is that localstorage,localstorage can be said to be an optimization of cookie, which makes it easy to store data on the client side and will not be transferred with HTTP, but it is not without problems:

The size of ① localstorage is limited to about 5 million characters, which varies from browser to browser.

② localstorage is not readable in privacy mode

③ localstorage is essentially reading and writing files, and if there is a lot of data, it will be stuck (firefox will import the data into memory at once, which is scary when you think about it)

④ localstorage cannot be crawled by crawlers. Do not use it to completely replace URL parameters.

All of the above problems can be avoided, so we should focus on how to use localstorage and how to use it correctly.

The use of localstorage

Basic knowledge

There are two types of localstorage storage objects:

① sessionStrage: session means conversation. Session here means that when a user visits a website, the validity period of the session object is only this long during the period from entering the site to closing the site.

② localStorage: save the data on the client hardware device, whatever it is, which means the data will still be there the next time you turn on the computer.

The difference between the two is that one is kept temporarily and the other is preserved for a long time.

Here is a simple code to illustrate its basic use:

XML/HTML Code copies content to the clipboard

SessionStorage

LocalStorage

Save data

Read data

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 [XSS _ clean] = sessionStorage.getItem ('msg')

} else {

MSG [XSS _ clean] = localStorage.getItem ('msg')

}

}

Real scene

In practice, the use of localstorage generally has the following requirements:

① caches general information, such as the departure city of the search page, reaches the city, and does not locate information in real time.

② caches city list data, which tends to be large

Each piece of cached information in ③ needs to be tracked. For example, when the server notifies the city data update, it is automatically set to expire on the last visit.

Each piece of information in ④ has an expiration date status, and the server needs to pull the data outside the expiration date.

XML/HTML Code copies content to the clipboard

Define ([], function () {

Var Storage = _ .inherit ({

/ / default attribute

Propertys: function () {

/ / proxy object. Default is localstorage.

This.sProxy = window.localStorage

/ / 60 * 60 * 24 * 30 * 1000 ms = = 30 days

This.defaultLifeTime = 2592000000

/ / Local cache is used to store the mapping of all localstorage key values to expiration dates.

This.keyCache = 'SYSTEM_KEY_TIMEOUT_MAP'

/ / when the cache capacity is full, the number of caches deleted each time

This.removeNum = 5

}

Assert: function () {

If (this.sProxy = null) {

Throw 'not override sProxy property'

}

}

Initialize: function (opts) {

This.propertys ()

This.assert ()

}

/ *

New localstorage

Data format includes unique key value, json string, expiration date, deposit date

Sign is the formatted request parameter, which is used to return new data for different parameters of the same request. For example, if the list is Beijing, and then it is switched to Shanghai, the cached data will be updated according to different tag. Tag is equivalent to a signature.

Each key value caches only one piece of information.

, /

Set: function (key, value, timeout, sign) {

Var _ d = new Date ()

/ / date of deposit

Var indate = _ d.getTime ()

/ / the final saved data

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) {

/ / when the localstorage is full, clear it all

If (e.name = = 'QuotaExceededError') {

/ / this.sProxy.clear ()

/ / when the localstorage is full, choose to delete the data closest to the expiration time, which will have some impact, but it feels better than clearing it all. If there are too many caches, this process is more time-consuming, within the 100ms.

If (! this.removeLastCache ()) throw 'data storage capacity is too large'

This.set (key, value, timeout, sign)

}

Console & & console.log (e)

}

Return false

}

/ / Delete expired cache

RemoveOverdueCache: function () {

Var tmpObj = null, I, len

Var now = new Date () .getTime ()

/ / take out key-value pairs

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

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report