cookie最大的缺陷是在每一次HTTP請(qǐng)求中都會(huì)攜帶所有符合規(guī)則的cookie數(shù)據(jù).這會(huì)增加請(qǐng)求響應(yīng)時(shí)間,特別是XHR請(qǐng)求. 在HTML5中使用sessionStorage
和localStorage
代替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;
}
更多建議: