本地存储与 Cookie [英] Local Storage vs Cookies

查看:38
本文介绍了本地存储与 Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过将所有 cookie 移动到本地存储来减少我网站的加载时间,因为它们似乎具有相同的功能.除了明显的兼容性问题外,使用本地存储替换 cookie 功能是否有任何优点/缺点(尤其是在性能方面)?

I want to reduce load times on my websites by moving all cookies into local storage since they seem to have the same functionality. Are there any pros/cons (especially performance-wise) in using local storage to replace cookie functionality except for the obvious compatibility issues?

推荐答案

Cookie 和本地存储有不同的用途.Cookie 主要用于读取服务器端,本地存储只能由客户端读取.所以问题是,在您的应用程序中,谁需要这些数据—客户端还是服务器?

Cookies and local storage serve different purposes. Cookies are primarily for reading server-side, local storage can only be read by the client-side. So the question is, in your app, who needs this data — the client or the server?

如果是您的客户端(您的 JavaScript),那么请务必切换.发送每个 HTTP 标头中的所有数据是在浪费带宽.

If it's your client (your JavaScript), then by all means switch. You're wasting bandwidth by sending all the data in each HTTP header.

如果是您的服务器,本地存储就没有那么有用了,因为您必须以某种方式转发数据(使用 Ajax 或隐藏表单字段或其他方式).如果服务器只需要每个请求总数据的一小部分,这可能没问题.

If it's your server, local storage isn't so useful because you'd have to forward the data along somehow (with Ajax or hidden form fields or something). This might be okay if the server only needs a small subset of the total data for each request.

无论如何,您都希望将会话 cookie 保留为 cookie.

根据技术差异,以及我的理解:

As per the technical difference, and also my understanding:

  1. 除了作为一种旧的数据保存方式之外,Cookie 还为您提供了 4096 字节的限制(实际上为 4095)—它是每个 cookie.本地存储空间高达每个域 5MBSO Question 也提到了.

  1. Apart from being an old way of saving data, Cookies give you a limit of 4096 bytes (4095, actually) — it's per cookie. Local Storage is as big as 5MB per domainSO Question also mentions it.

localStorageStorage 接口的实现.它存储的数据没有到期日期,并且通过JavaScript清除,或清除浏览器缓存/本地存储的数据—与 cookie 过期不同.

localStorage is an implementation of the Storage Interface. It stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser Cache / Locally Stored Data — unlike cookie expiry.

这篇关于本地存储与 Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆