Tip 1: 使用web storage代替cookie

cookie最大的缺陷是在每一次HTTP请求中都会携带所有符合规则的cookie数据.这会增加请求响应时间,特别是XHR请求. 在HTML5中使用sessionStoragelocalStorage代替cookie是更好的做法.

这另种方法可以将数据永久或者以session时间存储在用户本地.数据不会随着HTTP请求传递.所以我们优先使用web storage,仅仅使用cookie作为替代方案.

  1. // if localStorage is present, use that
  2. if (('localStorage' in window) && window.localStorage !== null) {
  3. // easy object property API
  4. localStorage.wishlist = '["unicorn", "Narwhal", "deathbear"]';
  5. } else {
  6. // without sessionStorage we'll have to use a far-future cookie
  7. // with document.cookie's awkward API
  8. var date = new Date();
  9. date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));
  10. var expires = date.toGMTString();
  11. var cookiestr = 'wishlist=["unicorn", "Narwhal", "deathbear"];' +
  12. ' expires=' + expires + '; path=/';
  13. document.cookie = cookiestr;
  14. }