cookie最大的缺陷是在每一次HTTP請求中都會攜帶所有符合規則的cookie數據.這會[增加請求響應時間](http://yuiblog.com/blog/2007/03/01/performance-research-part-3/),特別是XHR請求. 在HTML5中使用`sessionStorage`和`localStorage`代替cookie是更好的做法.
這另種方法可以將數據永久或者以session時間存儲在用戶本地.數據不會隨著HTTP請求傳遞.所以我們優先使用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;
}
~~~