1. Method
javaScript
There are four main methods of local caching:
- cookies
- sessionStorage
- localStorage
- indexedDB
cookie
Cookie
, a type of “small text file”, refers to the data that some websites store on the user’s local terminal in order to identify the user’s identity. It is to solve the problems caused by HTTP
statelessness
As a small piece of text data that generally does not exceed 4KB, it consists of a name (Name), a value (Value) and several other optional attributes used to control the cookie
validity period, security, and usage scope. composition
However, cookie
will be sent in every request. If HTTPS
is not used and encrypted, the information stored in it can be easily stolen, leading to security risks.
For example, on some websites that use cookie
to stay logged in, if the cookie
is stolen, it is easy for others to use your cookie
to impersonate you. Login to your website
The commonly used attributes of cookie
are as follows:
- Expires is used to set the expiration time of cookies.
Expires=Wed, 21 Oct 2015 07:28:00 GMT
- Max-Age is used to set the number of seconds that need to pass before the cookie expires (higher priority than
Expires
)
Max-Age=604800
Domain
specifies the host name to whichCookie
can be deliveredPath
specifies aURL
path. This path must appear in the path of the resource to be requested before theCookie
header can be sent.
Path=/docs # Resources under /docs/Web/ will have Cookie headers
Cookie
marked asSecure
should only be sent to the server through requests encrypted by theHTTPS
protocol
From the above, we can see that the role of cookie
is not designed for caching. It just borrows the characteristics of cookie
to implement caching.
The use of cookie
is as follows:
document.cookie = 'name=value';
Regarding the modification of cookie
, first make sure that the domain
and path
attributes are the same. If one of them is different, a new one will be created. New cookie
Set-Cookie:name=aa; domain=aa.net; path=/ # Server settings document.cookie =name=bb; domain=aa.net; path=/ # Client settings
Finally, the most common way to delete cookie
is to set an expiration event for cookie
, so that cookie
will be deleted by the browser after it expires.
localStorage
HTML5
New method, compatible with IE8 and above browsers
Features
- Life cycle: Persistent local storage, unless the data is actively deleted, the data will never expire
- Stored information is shared within the same domain
- When this page operates (adds, modifies, deletes)
localStorage
, this page will not trigger thestorage
event, but other pages will trigger thestorage
event. - Size: 5M (related to the browser manufacturer)
localStorage
is essentially reading a string. If you store a lot of content, it will consume memory space and cause the page to become stuck.- Restricted by the same-origin policy
Let’s take a look at the use of localStorage
set up
localStorage.setItem('username','cfangxu');
Obtain
localStorage.getItem('username')
Get key name
localStorage.key(0) //Get the first key name
delete
localStorage.removeItem('username')
Clear all storage at once
localStorage.clear()
localStorage
is not perfect, it has two shortcomings:
- Cannot set expiration time like
Cookie
- Only strings can be stored, objects cannot be stored directly.
localStorage.setItem('key', {name: 'value'}); console.log(localStorage.getItem('key')); // '[object, Object]'
sessionStorage
The usage methods of sessionStorage
and localStorage
are basically the same. The only difference is the life cycle. Once the page (session) is closed, sessionStorage
> Data will be deleted
Extended front-end storage method
indexedDB
is a low-level API for client-side storage of large amounts of structured data (including files/blobs). The API uses indexes to enable high-performance searches of this data
While Web Storage
is useful for storing smaller amounts of data, this approach is less useful for storing larger amounts of structured data. IndexedDB
provides a solution
Advantages:
- Theoretically there is no upper limit on storage capacity
- All operations are asynchronous and have higher performance than
LocalStorage
synchronous operations, especially when the amount of data is large - Native support for storing
JS
objects - It is a serious database, which means it can do everything the database can do.
Disadvantages:
- The operation is very cumbersome
- There is a certain threshold in itself
The basic steps for using indexedDB
are as follows:
- Open the database and start a transaction
- Create an
object store
- Construct a request to perform some database operation, like adding or extracting data, etc.
- Wait for the operation to complete by listening for the correct type of
DOM
event. - Perform some operation on the result of the operation (can be found in the
request
object)
Regarding the use of indexdb
, it will be more cumbersome. You can use the Godb.js
library for caching to minimize the difficulty of the operation.
2. Difference
The main differences between cookie
, sessionStorage
, and localStorage
are as follows:
- Storage size:
cookie
data size cannot exceed4k
. AlthoughsessionStorage
andlocalStorage
also have storage size restrictions, they are smaller thancookie
is much larger and can reach 5M or more - Validity time:
localStorage
stores persistent data. The data is not lost after the browser is closed unless the data is actively deleted;sessionStorage
data is automatically deleted after the current browser window is closed;cookie
The setcookie
is valid until the expiration time, even if the window or browser is closed - The interaction method between data and server,
cookie
data will be automatically transferred to the server, the server can also writecookie
to the client;sessionStorage
andlocalStorage
will not automatically send data to the server, but will only save it locally.
3. Application scenarios
After understanding the above-mentioned front-end caching methods, we can look at the usage options for different scenarios:
- To mark users and track user behavior, it is recommended to use
cookie
- Suitable for long-term local storage of data (tokens), it is recommended to use
localStorage
- For one-time login of sensitive accounts, it is recommended to use
sessionStorage
- When storing a large amount of data or when online documents (rich text editors) save editing history, it is recommended to use
indexedDB
The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Cloud native entry-level skills treeHomepageOverview 16,793 people are learning the system