Are there any drawbacks to using localStorage instead of Cookies?

前端 未结 4 1396
花落未央
花落未央 2020-12-23 19:30

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 tre

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-23 19:45

    Usability

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

    Performance

    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

    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.

    Your Questions

    1. You are not using this data server side, so you don't need a cookie. localStorage is never sent to the server unlike a cookie.
    2. If the user disables the cookies, localStorage will not work either.

    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 :(
    }
    

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

提交回复
热议问题