阅读(4240)
赞(16)
Tip 1: 使用web storage代替cookie
2016-02-24 16:05:06 更新
cookie最大的缺陷是在每一次HTTP请求中都会携带所有符合规则的cookie数据.这会增加请求响应时间,特别是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;
}
← 简介