許多開發者誤以為 localStorage 僅是「容量更大的 Cookie」。本文揭示其本質差異、核心優勢、適用場景,並提供低版本瀏覽器兼容方案。
| 特性 | Cookie | localStorage |
|---|---|---|
| 容量 | ~4KB | 5-10MB |
| 隨請求發送 | 是(每次 HTTP 諜求攜帶) | 否(純客戶端存儲) |
| 過期控制 | 手動設置 Expires/Max-Age | 永久,除非手動清除 |
| 跟蹤風險 | 高(自動上傳) | 低(需 JS 讀取後主動發送) |
關鍵優勢:localStorage **不隨 HTTP 請求自動發送**,極大節省頻寬,避免 Cookie 污染靜態資源域名優化。
storage 事件實現多標籤同步狀態。IE 6/7 不支持 localStorage,可用 userData 行為模擬:
<!--[if lte IE 7]>
<script>
var localStorage = {
_elem: document.createElement('div'),
_init: function() {
this._elem.style.display = 'none';
this._elem.addBehavior('#default#userData');
document.body.appendChild(this._elem);
this._elem.load('localStorage');
},
getItem: function(key) { this._init(); return this._elem.getAttribute(key); },
setItem: function(key, val) { this._init(); this._elem.setAttribute(key, val); this._elem.save('localStorage'); },
removeItem: function(key) { this._init(); this._elem.removeAttribute(key); this._elem.save('localStorage'); }
};
</script>
<![endif]-->
或引入成熟 Polyfill:localStorage-polyfill、store.js。
IndexedDB 或 Web Worker。localStorage 可能拋異常,需 try-catch 保護。正確認知 localStorage 定位,釋放其真正價值。