当前位置:网站首页>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.
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
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.
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
边栏推荐
- 1、 JS introduction
- d3.js&nvd3. JS - how to set the y-axis range - d3 js & nvd3. js — How to set y-axis range
- Tiktok keyword search list interface, ultra detailed interface docking steps
- How to download and install stm32cubemx
- Redis subscribe connection timeout interrupt problem solution
- anaconda下安装pytorch
- MySQL query exercise
- 淘宝商品历史价格接口/商品历史价走势接口代码对接分享
- Founder of Starbucks: no longer open "public toilets" to non store consumers for safety reasons
- How can the small and medium-sized lighting industry make use of the digital transformation to stand out from the encirclement?
猜你喜欢
The method of SolidWorks modifying text font in engineering drawing
Explanation of JS event loop mechanism and asynchronous tasks
0.一些自己初学Solidworks的疑惑
HCIP_ Static experiment
Founder of Starbucks: no longer open "public toilets" to non store consumers for safety reasons
centos 安装mysql及设置远程访问
0. Quelques doutes au sujet de SolidWorks
DIY UAV (anonymous controller p2+f330 rack)
1. Learning sequence of SolidWorks modules
0. some doubts about learning SolidWorks for the first time
随机推荐
MySQL sorts according to the specified order of the specified fields
Custom exception class myexception
WARNING:tornado.access:404 GET /favicon.ico (172.16.8.1) 1.84ms [附静态文件设置]
filebeat采集日志到ELK
In order to resist the flood, the soldiers have been fighting for 89 hours. How many days and hours are there in total?
Penetration problem (main directory, password explosion, database uploading Trojan horse)
Numeric types in SQL. Try to avoid using null as the default value
Tiktok keyword search list interface, ultra detailed interface docking steps
Logstash failed to create queue
容器概念和云原生
[virt manager] remote management the problem of the floating mouse when starting the virtual machine
Learning record 4:einops / / cudnn benchamark=true // hook
Determination of ranking
MySQL queries difference sets (missing data) by linking tables based on an associated field
Determine whether a string is rotated from another string
PHP PNG to webp
Redis分布式集群搭建
Sky background map, navigation page lovefanfan top
DNS domain name resolution service
Three methods to make the scroll bar of div automatically scroll to the bottom