Tip 1: 使用web storage代替cookie

2018-02-24 16:05 更新

cookie最大的缺陷是在每一次HTTP請(qǐng)求中都會(huì)攜帶所有符合規(guī)則的cookie數(shù)據(jù).這會(huì)增加請(qǐng)求響應(yīng)時(shí)間,特別是XHR請(qǐng)求. 在HTML5中使用sessionStoragelocalStorage代替cookie是更好的做法.

這另種方法可以將數(shù)據(jù)永久或者以session時(shí)間存儲(chǔ)在用戶本地.數(shù)據(jù)不會(huì)隨著HTTP請(qǐng)求傳遞.所以我們優(yōu)先使用web storage,僅僅使用cookie作為替代方案.

// if localStorage is present, use that
if (('localStorage' in window) && window.localStorage !== null) {

  // easy object property API
  localStorage.wishlist = '["unicorn", "Narwhal", "deathbear"]';

} else {

  // without sessionStorage we'll have to use a far-future cookie
  // with document.cookie's awkward API
  var date = new Date();
  date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));
  var expires = date.toGMTString();
  var cookiestr = 'wishlist=["unicorn", "Narwhal", "deathbear"];' +
                  ' expires=' + expires + '; path=/';
  document.cookie = cookiestr;
}
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)