Thoroughly understand Html5 local storage technology (1) and html5 Storage Technology
I. Implementation of local client storage before H5
1. cookies
Cookies are widely used, but the following problems exist:
(1) Each http request is carried at the head, which wastes resources.
(2) Each domain name client can only store 4 K
(3) primary Domain pollution
(4) The plaintext transmission of cookies is insecure.
2. UserData (only supported by IE)
3. Other non-mainstream solutions
2. H5-related storage knowledge
1. Local Storage WebStorage (localstorage & sessionstorage)
Browser support
(1) Lifecycle
- Localstorage permanent storage unless it is removed or cleared, sessionstorage will be cleared during the page session period (the page will not be refreshed );
(2) API (same as ls and ss)
- Length // number of key-value pairs in storage read-only
- SetItem // Add key-value Pair key value
- GetItem // obtain key-value pairs based on the key
- Key // The key name can be obtained based on the index attribute
- RemoveItem // remove a key-Value Pair Based on the key
- Clear // clear
(3) storage type and size
- WebStorage storage string (as long as it can be serialized as a string)
- 5 MB per domain name
(4) storage events
The storage event is triggered when webStorage changes.
- Key: key name
- OldValue: Modify the previous value
- NewValue: the modified value.
- Url: the url of the page that triggers the change
- StorageArea: Storage changed
(5) Precautions
- Data storage in different browsers is independent of each other, and chrome's localStorage cannot be accessed on ff.
- Check whether the browser supports the object during use (do not use window. localStorage to check whether the object exists. set a piece of data and perform exception capture)
- Since ls is permanently stored, We need to update the policy to control expiration.
Function set (key, vel) {var curTime = new Date (). getTime (); localStorage. setItem (key, JSON. stringify ({data: vel, time: curTime});} function get (key, exp) {var data = locaStorage. getItem (key); var dataObj = JSON. parse (data); if (new Date (). getTime ()-dataObj. time <exp) {return dataObj. data;} else {alert ('expired! ');}}
- Data cannot be shared between subdomains-data is transmitted using the cross-origin method
Note:
Although webstorage is good, it is not used to completely replace cookies. It should be used when cookies should not be used but must be used.
After WebStorage is available, the cookie should only do what it should do-as a channel for interaction between the client and the server, and maintain the client status.