使用localStorage而不是Cookie有什么缺点吗? [英] Are there any drawbacks to using localStorage instead of Cookies?

查看:610
本文介绍了使用localStorage而不是Cookie有什么缺点吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我以前的网站上,我曾经使用Cookie在首次访问时显示首页。效果很好(参见这里的例子),但使用cookie并不是今天的时尚,所以我想尽可能避免它。

On my previous websites, I used to use a cookie to display a pre-home page only on the first visit. That worked great (see for example here), but using cookies is not so trendy today, so I want to avoid it as much as possible.

现在,我的新网站项目几乎总是通过javascript(显示一个modalbox)预启动,所以我不需要在服务器上执行任何操作侧。我正在考虑使用HTML5 localStorage而不是cookie,如果浏览器没有localStorage,那么就会使用cookies。这是个好主意吗?

Now, my new website projects almost always have pre-home launched via javascript (showing a modalbox), so I don't need to do any action on the server side. I'm considering to use HTML5 localStorage instead of cookies, with a fallback on cookies if the browser does not have localStorage. Is this a good idea? What is the impact in terms of usability, privacy protection and website performance?

使用localStorage可以提高禁用Cookie的用户的可用性。但我知道一些HTML5功能只在一些浏览器中选择(像geolocalisation)。在任何浏览器上有没有像localStorage这样的限制?

Using localStorage will improve usability for users that have disabled cookies. But I know that some HTML5 features are only opt-in (like geolocalisation) in some browser. Is there any restriction like that for localStorage on any browser ? Is there any case where I will get a JS error if localStorage is available but deactivated for my site ?

推荐答案

可用性

如果localStorage可用, >

用户不知道您是使用localStorage还是cookie。

Usability

The user will not know if you are using localStorage or a cookie. If a user disable cookies, localStorage will not work either.

没有明显的速度差异这两种方法。

There is no noticeable speed difference between the two methods.

sessionStorage仅适用于浏览器标签页的会话。如果关闭标签页,会话将丢失,数据也会丢失,这类似于任何后端语言的会话变量。

sessionStorage is only for that browser tab's session. If you close the tab, the session will be lost and the data will be lost too, it's similar to a session variable on any backend language.

localStorage将可用于浏览器中的任何选项卡或窗口,并且将一直存在,直到被用户或程序删除。与Cookie不同,您不能设置过期。

localStorage will be available for any tab or window in the browser, and will exist until it is deleted by the user or the program. Unlike a cookie, you cannot setup expiration. localStorage has a much larger storage limit as well.


  1. 不使用此数据服务器端,因此您不需要cookie。

  2. 如果用户禁用了cookie,localStorage也不会工作。



后退示例



您可以使用Modernizr验证localStorage是否可用,如果没有,请使用存储cookie。

Fallback Example

You can use a Modernizr to verify if localStorage is available and if not, use store a cookie instead.

if (Modernizr.localstorage) {
    // supports HTML5 Storage :D
} else {
    // does not support HTML5 Storage :(
}

您也可以放弃Modernizr并使用检查 typeof Storage!=='undefined'

You can also forego Modernizr and use the check typeof Storage !== 'undefined'.

这篇关于使用localStorage而不是Cookie有什么缺点吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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