当前位置:网站首页>Differences and uses among cookies, localstorage, sessionstorage, and application caching

Differences and uses among cookies, localstorage, sessionstorage, and application caching

2022-06-13 08:38:00 Medlar plus

Web Storage

HTML5 Two new storage methods are added :localStorage、sessionStorage, And before that , The main use is cookies Storage . Here are the differences and application scenarios of the three :

cookies Storage

Introduce

cookies It is actually a small text data ( No more than 4KB) Each browser will have a special folder to store cookies data ,cookies The main contents are key/value Values and for control cookie The period of validity 、 Security 、 Several optional attributes of the usage range consist of . We can see in the browser cookie.
 Insert picture description here
One cookie The general composition and function of the record are as follows

form
  • Namge/Value: Set up Cookie The name and corresponding value of , For authentication Cookie,Value Values include Web The access token provided by the server .
  • Expires/Max-Age: Set up Cookie Life span of (GMT Format ), The attribute value defaults to , For conversational Cookie, Save only in client memory , And fail when the user closes the browser ; persistence Cookie Will be saved on the user's hard disk , Until the expiration date or the user clicks directly in the web page “ Cancellation ” It doesn't work until the button ends the session .Max-Age by http/1.1 The name in the agreement , The unit is seconds .max-age There are three possibilities : negative 、0、 Positive numbers . negative : The period of validity session;0: Delete cookie; Positive numbers : The validity period is the creation time + max-age.
  • Path: Defined Web You can visit this Cookie The catalog of .
  • Domain: Specifies that you can access the Cookie Of Web Site or domain ,domain Forbid setting .org .com Such as the general top-level domain name , Mainly to reduce the risk of Cookie The scope of the attack .
  • Secure: Specify whether to use HTTPS Security protocol sends Cookie, If it is set, it is equivalent to sending a security request only (https) Only when cookie Data is substituted into the request . Use HTTPS Security protocols , Can protect Cookie In browser and Web No stealing and tampering during the transmission between servers .
  • HTTPOnly: Prevent client-side scripts from passing document.cookie Attribute access Cookie, Help to protect Cookie Not stolen or tampered with by cross site scripting attacks .

More about Cookies You can view the information and security protection of Baidu Encyclopedia

Use scenarios

cookie Data in , Every time a browser request is sent , Will be automatically put into http In request , The browser has a configuration switch to determine whether each request needs to include these cookie data , Based on this feature ,cookie It is used to store the data that must be transmitted for each request , Such as identity authentication information .

operation cookie

We can execute on the console document.cookie To get or set non HttpOnly Type of cookie data , Data attributes are separated by semicolons .

To modify a cookie, Just reassign it , The old value will be covered by the new value . But pay attention to , Setting new cookie when ,path/domain These options must be old cookie Keep the same . Otherwise, the old value will not be modified , Instead, a new cookie.

Delete one cookie It's quite simple , It's also a reassignment , Just put this new cookie Of expires Just set the option to a past point in time . But also pay attention to ,path/domain/ These options must be old cookie Keep the same .

Be careful :cookie Middle comma , A semicolon , Spaces are treated as special symbols , If key and value This exists in 3 Special characters , Need to use escape Encoding ,unescape decode .

localStorage

localStorage There is no time limit for data storage , The storage space is generally 5M
 Insert picture description here

Common methods

  • Save the data :localStorage.setItem(key,value);
  • Reading data :localStorage.getItem(key);
  • Delete individual data :localStorage.removeItem(key);
  • Delete all data :localStorage.clear();
  • Get an index of key:localStorage.key(index);
  • Determine whether a certain attribute value exists :localStorage.hasOwnProperty(key);

localStorage The data in is key/value Stored in , We can use it directly . perhaps [] To access the specified key Of value value , as follows :

//  More recommended .setItem,.getItem Way to obtain 
localStorage.name = 'myname'
localStorage['name'] //myname

By default localStorage Of value Values can only store strings , We can go through JSON The way of transformation , Storing arrays or objects .

var users = [
    {
        name: "xiaoming",
        grade: 1
    },
    {
        name: "teemo",
        grade: 3
    }
]
// write in 
var usersStr = JSON.stringify(users);
localStorage.user = usersStr
// Read 
var newUser = JSON.parse(localStorage.user)

sessionStorage

In view of a session Data storage , When you close your browser or close a web page , The stored data will be cleared , The storage space is generally 5M.
 Insert picture description here

Common methods

  • Save the data :sessionStorage.setItem(key,value);
  • Reading data :sessionStorage.getItem(key);
  • Delete individual data :sessionStorage.removeItem(key);
  • Delete all data :sessionStorage.clear();
  • Get an index of key:sessionStorage.key(index);

Be careful :localStorage and sessionStorage The only difference between the two is the length of time they store data , When storing data , Is to use string How to store , So from storage You should pay attention to the problem of type conversion when fetching data .

H5 Application caching

HTML5 Provides application caching , By creating a cache manifest File to create web Offline version of the app . This means that we can access... Offline .

The application cache depends on manifest file ,manifest The file tells the browser what is cached and what is not cached . The contents of the document can be divided into three parts :

  • CACHE MANIFEST - The files listed under this heading will be cached after the first download
  • NETWORK - The files listed under this heading need to be connected to the server , And will not be cached
  • FALLBACK - The documents listed under this heading specify the fallback page when the page is inaccessible ( such as 404 page )

Here's a manifest Examples of documents :

CACHE MANIFEST        
# 2012-02-21 v1.0.0  This is the note , Changing the annotation also causes the browser to update the cache 
/theme.css        
/logo.gif        
/main.js        
        
NETWORK:        
login.php        
        
FALLBACK:       
#  The following parameter is the first url It's resources , The second is the substitute 
/html/ /offline.html 

How to update the cache

After the application is cached , Will continue to maintain the cache , Know the following :

  • User clears browser cache (clear cache)
  • manifest The document was modified
  • The application updates the application cache

Application caching benefits

  • Offline browsing - Users can use their apps while they are offline
  • Speed - Cached resources load faster
  • Reduce server load - The browser will only download updated or changed resources from the server .

Be careful : If the file we cache on the server is modified , The browser does not update the cache , So we need to update manifest File to trigger cache updates .

HTML5 Usage scenarios for application caching

Application caching mainly provides static resources ( Static page 、css、 Image, etc ) The cache of , When there are some elements or resources on the page that rarely change, they are , You can use the application cache method to cache it , Avoid duplicate requests , Reduce server load .

Reference link

Cookie Introduce

Application cache

原网站

版权声明
本文为[Medlar plus]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202270539357695.html