Front-end data storage JS-

The client application store is a great way for the rapid performance optimization is performed. By storing the data in the browser, users do not always get the same request to the server information. When you are offline, using locally stored data rather than it is useful to request data on a remote server, or even online users can also benefit from it. The client storage can be achieved by these techniques: cookie, sessionstorage, Local Storage (more accurately, "Web Storage"), IndexedDB, userData.

A, cookie

1, cookie role  

  When it comes to cookie, cookie actually has two main functions, the first function is used to solve the shortcomings http stateless session information stored in the client, record a user's status, while the second function is what we now often use cookie store some other data in the client

2, cookie configuration

  Generally, cookie consists of the following pieces of information stored in the browser constituted

  (1) Name: determine a unique name of the cookie

  (2) values: String value stored in the cookie, the values ​​must be encoded URL

  (3) field: cookie which is effective for the domain, the domain request sent to all the cookie will include information

  (4) path: the path for the specified domain, cookie should be sent to the server

  (5) Failure Time: time stamp indicating when the cookie should be deleted

  (6) Safety signs: After you specify, cookie sent to the server only when using an SSL connection

 

3, how to use a cookie to store data

  In general, there are two ways to generate a cookie, one is designated Set-Cookie http specified when the server sends a response, we can use another cookie generate js

  Since the cookie need URL encoding, so when writing and reading cookie cookie when we need to be encoding and decoding operations, for convenience, we can write the operating target of a cookie

Copy the code
var CookieUtil = {
    get: function(name) {
        var cookieName = encodeURIComponent(name) + "=",
              cookieStart = document.cookie.indexOf(cookieName),
              cookieValue = null;
         
         if(cookieStart > -1) {
             var cookieEnd = document.cookie.indexOf(";", cookieStart);
             if (cookieEnd == -1) {
               cookieEnd = document.cookie.length;
             }
             cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
         }
         return cookieValue;
    },
    set: function(name, value, expires, path, domain, secure) {
        var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(valeu);
        if(expires instanceof Data) {
            cookieText += ";expires=" + expires.toGMTString();
        }
        if(path) {
            cookieText += ";path=" + path;
        }
        if(domain) {
            cookieText += ";domain=" + domain;
        }
        if(secure) {
            cookieText += ";secure";
        }
        document.cookie = cookieText;
    }
    unset: function(name, path, domain, secure) {
        this.set(name, "", new Date(0), path, domain, secure);
    }
}
Copy the code

  When we think of some state data is stored in a cookie, such as storage of whether the user clicks on the ad, it can be set as follows

CookieUtil.set("ifClick", "true");

  When we want to determine whether the user clicks on an ad, you need to come up with data from the cookie, so you can get data like this

CookieUtil.get("ifClick");

  IfClick by acquiring the data from our deposit cookie, we can get the corresponding value is true, Well, this user has clicked the ad, do not show it red dot

 

4, cookie shortcomings

  Although the cookie may store some data, but the memory is still below some drawbacks

  (1) cookie transferred back and forth between the client and server side, will waste unnecessary resources

  Storage size (2) has a limit cookie, for each field, generally only 20 disposed cookie, each cookie can not exceed the size of 4KB

  (3) cookie safety, cookie as stored in the client, any data they contain can be accessed by others, cookie security is relatively low

 

Two, Web storage mechanism

Next, we have to say about it in the store html5, mainly sessionStorage and localStrorage

1. What is the Web Storage

  Web Storage is also a client in a mechanism for storing data, the main purpose is to overcome some of the limitations brought about by the cookie when data needs to be strictly controlled on the client, without the data on the client and the server back and forth between the transmit and store large amounts of data across sessions

  In general, Web Storage contains the definitions of both audiences, sessionStorage and globalStorage, and now localStorage in revised html5 specification replaces globalStorage as persistent client-side data plan, then, let's look at what they have distinguish it

 

2、sessionStorage

(1) What is sessionStorage

  sessionStorage objects are stored data specific to a session, that is, data is saved only to the browser is closed, the object as a session cookie, will disappear when the browser is closed, the data stored in sessionStorage can exist across a page refresh

(2) How to use the stored data sessionStorage

  Since sessionStorage Storage object is an instance, it may be used when storing data setItem () or directly to the new attribute data stored

// Use the method of storing data 
sessionStorage.setItem ( "ifClick", "to true"); 

// attribute used to store data 
sessionStorage.ifClick = "true";

  When we want to get some data, you can use to get data getItem

sessionStorage.getItem("ifClick");

  We are now successfully acquired value ifClick friends, of course, can be obtained through the length of the value sessionStorage property and key () method

(3) sessionStorage features

  a, same origin policy restrictions, if you want to operate on the same sessionStorage between pages, the pages must be in the same protocol, under the same name and the same host port

  B, a single tab limits, in a single operation limitation sessionStorage tab, homology in this tab page views can share data sessionStorage

  c, only stored locally, seesionStorage data will not follow an HTTP request to the server, together, will only take effect locally, and clear the data after you close the tab

  d, storage, seesionStorage using the storage key, value way

  e, storage upper limit: limit different browser stores are not the same, but most browsers the upper limit in the following 5MB

 

3、globalStorage

(1) What is globalStorage

  As part of the initial Web Storage, the purpose of this object is to store data across the session, but there are certain access restrictions, has now been replaced localStorage globalStorage

(2) How to use the stored data globalStorage

  To use the globalStorage, first specify which domains are accessible to the data, can be implemented by using the property tag brackets

globalStorage["aaa.com"].ifClick = "true";

  In the above code, the visit is for the domain name aaa.com storage space, and this storage space for aaa.com and all of its sub-domains are accessible, we can do to get data like this

globalStorage[aaa.com].getItem("ifClick");

  Because globalStorage now less use, if you want to use, or use localStorage

(3) globalStorage features

  If you do not use removeItem () or delete deleted, or the user does not clear your browser cache, the data will be saved on disk, so it is suitable for the client to store documents or long-term saving user preferences

 

4、localStorage

(1) What is the localStorage

  localStorage object revised html5 specification as to persist client data solutions has brought globalStorage, and globalStorage different, you can not specify any access rules to localStorage, because the rules have been pre-booked, to access the same localStorage object page It must come from the same domain name, using the same protocol, in the same port

(2) How to use the stored data localStorage

  Storage is because the localStorage instance, can be used like to use it as sessionStorage

localStorage.setItem("ifClick","true");

  When we want to get the data, you can get like this

localStorage.getItem("ifClick");

  In globalStorage data stored in the same data and stored in localStorage in, follow the same rules, to retain data through js or delete user clears the browser cache

(3) localStorage features

  a, localStorage will be the first time the requested data is stored directly to a local, this is equivalent to a size 5M for the front page of the database, compared to the cookie can save bandwidth, but this is only in the high version of the browser only in support of

  b, all current browsers will put localStorage value type is defined as a string type, this conversion takes some of us everyday more common JSON object type

  c, the localStorage is essentially a reading of the string, if the stored content and more words will consume memory space will cause the page to change card

  Finally, and we want to say is, sessionStorage and localStorage have overcome some of the limitations of the cookie, they have many features in common, the only one difference is localStorage localStorage and sessionStorage belong to permanent storage, and sessionStorage belong to the time when the session ends , sessionStorage the key is to be emptied.

 ps: [every browser supports the size of the localstorage is not the same, chrome is 5M, IE10 is 1630K. Js can use the following anonymous function test different browsers to support the size of localstorage]

(function() {
if(!window.localStorage) {
console.log('当前浏览器不支持localStorage!')
}
var test = '0123456789';
var add = function(num) {
num += num;
if(num.length == 10240) {
test = num;
return;
}
add(num);
}
add(test);
var sum = test;
var show = setInterval(function(){
sum += test;
try {
window.localStorage.removeItem('test');
window.localStorage.setItem('test', sum);
console.log(sum.length / 1024 + 'KB');
} catch(e) {
alert(sum.length / 1024 + 'KB超出最大限制');
clearInterval(show);
}
}, 0.1)
})()

 

Three, the IndexedDB

1, Why IndexedDB

  Data storage conventional browser program, not suitable for storing large amounts of data: Cookie size of not more than 4KB, and each request back to the server; the LocalStorage between 2.5MB to 10MB (various different browsers), and does not provide search function, can not create a custom index, therefore, a need for a new solution, which is the background of the birth IndexedDB

 

2. What is IndexedDB

  In layman's terms, IndexedDB local database is provided by the browser, it can be created and manipulated web scripts, IndexedDB allows storing large amounts of data, providing an interface to find, but also indexed, LocalStorage these are not available, it is the type of database words, IndexedDB does not belong to relational databases (SQL queries are not supported), closer to NoSQL database

 

3, IndexedDB features

  a, of the storage key: internal IndexedDB using object repository (object store) store data, all types of data can be directly stored, including JavaScript object, object repository, the data stored in the form of "key pair", each primary key has a corresponding data record, the primary key is unique and can not be duplicated, otherwise it will throw an error

  B, Induction: IndexedDB not locked when operating the browser, the user can still perform other operations, which in contrast to the LocalStorage, the latter operation is synchronous, asynchronous designed to prevent read and write large amounts of data, the down page which performed

  c, support services: IndexedDB support services (transaction), this means that in a series of steps, as long as the step fails, the entire transaction will have been removed, the database is rolled back to the state before the transaction occurs, there is only rewriting a portion of data Happening

  d, homologous restriction: IndexedDB by homologous restriction, each corresponding to a database to create its domain name, the page can only access the database under its own domain name, but can not access the cross-domain database

  E, large storage: IndexedDB LocalStorage larger than the storage space, generally less than 250MB, or even no limit

  F, support binary storage: IndexedDB can store not only the string, binary data can also be stored (an ArrayBuffer Blob object and objects)

  

Four, IEs user data

Although H5 can be carried out by localstorage data storage and sessionstorage, but lower version ie do not support it, how can this do? In order to store data ie, Microsoft through a custom behavior introduces the concept of persistent user data

1. What is userData

  userData is a data storage of ie, userData storing UserData by writing data to a storage area (UserData Store) to store data, the data stored on the userData client in XML format, is only applicable to storage UserData IE browser after saving UserData store, even though IE browser is closed or refreshed, enter the next page, the data can be reloaded without losing, that is, the data will always exist unless you delete or artificially set by the script expiration date data

  In general, userData allow each document to save up to 128KB of data, up to 1MB of data per domain name, is not it will be larger than the data stored in the cookie do?

 

2, how to store data userData

  If we want to use userData store data, you must first specify the css userData behavior on an element

<div style="behavior:url(#default#userData)" id="dataStore></div>

  Once the element used userData behavior, then you can use the setAttribute () method to save the data in the above, in order to submit the data to the browser cache, you must also call the save () method and tell it the name you want to save the data space , name data space can be completely arbitrary, only used to distinguish different data sets

var dataStore = document.getElementById("dataStore");
dataStore.setAttribute("ifClick", "true");
dataStore.save("ClickInfo");

  In the above code, after storing data using setAttribute, call save method, specifies the name of the data space ClickInfo, after loading the next page, the same data space can be specified using the load method to retrieve data

dataStore.load("ClickInfo");
dataStore.getAttribute("ifClick");

  In the above code, the call to load () Get all the information ClickInfo data space, and the data can be accessed through the elements, and only after loading the exact completion of data before they can use, well, now we have successfully acquired ifClick to the value of friends, ifClick is true, Well, the ad has been clicked, does not show red dot

  If getAttribute () calls the name does not exist or is not loaded in the name, it returns null, we can also use removeAttribute () method to delete certain data

dataStore.removeAttribute("ifClick");

 

3, userData shortcomings

  (1) userData just for data storage ie the

  (2) userData access restrictions and restrictions on access to the cookie, must come from the same domain name, in the same path, and use the stored script to access the same protocol

  (3) userData data is not safe, not to store important information

 

------------------------------------------------------------------------------------------------------------

Original link: https://www.cnblogs.com/Yellow-ice/p/10507472.html

 

 

 ================================================== =========== dividing line ===================================== ================================================== =============

localStorage single page and monitor changes in different pages

1. The single-page monitor event storage

var orignalSetItem = localStorage.setItem;
localStorage.setItem = function(key,newValue){
var setItemEvent = new Event("setItemEvent");
setItemEvent.key=key;
setItemEvent.newValue = newValue;
window.dispatchEvent(setItemEvent);
orignalSetItem.apply(this,arguments);
}


window.addEventListener("setItemEvent", function(e) {
              
console.log(e.key+"~~~"+e.newValue)
  
});

2. different pages

1) monitor the storage event

<!DOCTYPE html>
<html>
<head lang="en">
<title>A</title>
</head>
<body>
<script>
window.addEventListener("storage", function (e) {
alert(e.newValue);
});
</script>
</body>
</html>

 

2) modify the localStorage

<!DOCTYPE html>
<html>
<head lang="en">
<title>B</title>
</head>
<body>
<script>
localStorage.clear();
localStorage.setItem('foo', 'bar');
</script>
</body>
</html>
————————————————
原文链接:https://blog.csdn.net/qq_42076140/article/details/80307326

 

-------------------------------------------VIEW------ ------------------------

 

vue- rewrite localStorage.setItem method to monitor changes, real-time updates

When solving value changes locally stored js not real-time monitoring to the problem
Problem Description: We get the value of a certain localstorage in js inside, but later it may change, and we js performed only once can not get its value again, of course, you can refresh the page to obtain, but if we can not refresh the page, but the page at this time:
we can setItem localStorage method of rewriting, when calling setItem method to set the new value will be new Event ( 'setItemEvent')
but just an example of an event, and how to monitor it?
We can use window.dispatchEvent () this method to dispatch an event, let window to listen. A new instance out of this event is bound to monitor its window up call, when the call can get a new value setItem direct assignment can be
embodied
first in the src folder under the new utils, New tools.js, it will throw a dispatchEventStroage method
// rewrite setItem event, when using setItem triggered, window.dispatchEvent distribute event
dispatchEventStroage () {
const signSetItem = localStorage.setItem
localStorage.setItem = function (Key, Val) {
the let setEvent the Event new new = ( 'setItemEvent')
setEvent.key = Key
setEvent.newValue = Val
window.dispatchEvent (setEvent)
signSetItem.apply (the this, arguments)
}
}
in which global main.js introduction and use, and then call the dispatchEventStroage method to solve the problem will not take effect immediately setitemEvent
import Tools from '@ / utils / Tools'
Vue.use (Tools)
// to solve setItemEvent does not take effect immediately, use the event-dispatching forced higher
Tools.dispatchEventStroage ()
 

Then you can use the
field every time if we need to send a request to carry token, token may sometimes exist localstorage inside, but when the token is changed, we do not know js has changed, so we need to use the above method .
{reqHeaders = const
the Accept: 'text / JSON',
are returned after the // first logon token, token after each request field carries verify
token: localStorage.getItem ( 'token') || ''
}
// localStorage listening window of global events and updates setItem
window.addEventListener ( 'setItemEvent', function (E) {
reqHeaders.token = e.newValue
})
 
----------------
description link : https: //blog.csdn.net/weixin_43869192/article/details/85061248

 

Guess you like

Origin www.cnblogs.com/sylvia-Camellia/p/11589569.html