Summary of several commonly used browser caching methods and usage
To summarize now, a simple comparison is made for cookie, localStorage, and sessionStorage.
Contrast difference
characteristic | cookie | localStorage | sessionStorge |
---|---|---|---|
Storage size | 4k | 5M (different depending on the browser) | 5M (different depending on the browser) |
Access method | String | String (JSON translation) | String (JSON translation) |
Server communication | Carry header | No communication | No communication |
life cycle | Server generation, expiration time can be set | Always exist, unless cleaned up | Browser closed and empty |
Application scenario | Identify the user's identity, perform session tracking | Keep the data of the entire website for a long time | Temporarily save data in the same window (or tab) |
Detailed introduction
- cookie
- Cookies are often used to authenticate users at the front and back points and mark users. Because http is a stateless protocol (no memory), in order to solve the problem of http memory, session is used to manage cookies.
- The session will set a response header Set-Cookie on the server side; the client will receive it, and the browser will automatically bring the Cookie request header after sending the request. Too much sessionc storage will not be able to expand
- Extract the session and store it centrally.
- The service does not need to be stored, and the service can determine whether to log in by analyzing the information in the token. The token can carry information parsed by the cookie
- coolie—code
// sessionId通常存放在cookie当中 会话由浏览器控制 会话结束 session失效
u.cookie = {
}
//设置cookie
u.cookie.set = function(name, value, expiredays) {
var expires = ''
if (expiredays) {
var exdate = new Date()
exdate.setTime(exdate.getTime() + expiredays * (24 * 3600 * 1000))
expires = ';expires=' + exdate.toUTCString()
}
document.cookie = name + '=' + escape(value) + expires
}
//获取cookie
u.cookie.get = function(name) {
var arr = document.cookie.split('; ')
for (var i = 0; i < arr.length; i++) {
var temp = arr[i].split('=')
if (temp[0] === name) return unescape(temp[1])
}
return null
}
// 删除cookie
u.cookie.remove = function(name) {
u.cookie.set(name, '', -1)
}
- localStorage 、sessionStroage
- Used to temporarily save the data of the same window (or tab), which will be deleted after closing the window or tab
- Methods of storing objects:
javascript localStorage.setItem('cartInfor',JSON.stringify(data));
- Method to retrieve local storage objects
javascript JSON.parse(localStorage.getItem("cartInfor"))
- localStorage/sessionStroage-code is
compatible with android, setItem() supports storage object method
u.storage = {
};
//获取localStorage对象,兼容android(android原生系统老系统不支持localstorage)
function uzStorage() {
var ls = window.localStorage;
var isAndroid = (/android/gi).test(window.navigator.appVersion);
if (isAndroid) ls = os.localStorage();
return ls;
}
// 设置本地储存
u.storage.set = function (key, value) {
var v = value;
if (typeof v === 'object') {
v = JSON.stringify(v);
v = 'obj-' + v;
}
var ls = uzStorage();
if (ls) ls.setItem(key, v);
};
//获取本地储存
u.storage.get = function (key) {
var ls = uzStorage();
if (ls) {
var v = ls.getItem(key);
if (!v) return;
if (v.indexOf('obj-') === 0) return JSON.parse(v.slice(4));
else return v;
}
};
//删除本地储存中的某些数据
u.storage.remove = function (key) {
var ls = uzStorage();
if (ls && key) ls.removeItem(key);
};
// 清空本地储存所有数据
u.storage.clear = function () {
var ls = uzStorage();
if (ls) ls.clear();
};
to sum up
For cookies, sessionStorage, etc., there are generally encapsulated components in the front-end framework, such as vue-ls, js-cookie, etc. in vue. Knowledge is lively and learnt, and after knowing the principle, it is better to optimize and improve your own code level.