localStorage 应避免无变化重复写入、存储大对象或循环引用数据,每次操作需 try/catch 并有降级策略,清理需同步清除 localStorage、sessionStorage、IndexedDB 和 Service Worker 缓存。
直接覆盖写入不仅浪费 I/O,还可能触发不必要的 StorageEvent 监听器。尤其在频繁更新用户偏好、表单草稿等场景下,重复写入相同字符串会放大性能损耗。
JSON.stringify() 序列化后与 localStorage.getItem(key) 原值严格比对(===),避免对象引用或空格差异导致误判1 和 "1" 被当成不同值JSON.stringify(obj, Object.keys(obj).sort()) 统一键序后再比对,避免因属性顺序不同导致“假变更”localStorage 单条容量上限通常为 5–10MB(实际取决于浏览器),但真正瓶颈在于序列化/反序列化耗时和内存峰值。超过 100KB 的 JSON 字符串就可能造成 UI 卡顿,尤其在低端 Android WebView 中。
new Blob([jsonStr]).size 或 encodeURIComponent(jsonStr).length 预估字符串体积,超 64KB 就该拆分或换方案console.log() 输出的完整错误对象或 DOM 元素——它们含循环引用,JSON.stringify() 会静默失败并返回 "{}"
localStorage 不是稳定 API:私密模式下 Safari 会直接抛出 QuotaExceededError,旧版 iOS WebView 可能返回 null 而非抛错,某些定制 ROM 浏览器甚至禁用该 A
PI。
getItem()、setItem()、removeItem() 都必须包裹 try/catch,不能只在初始化时检测一次window.__ls_error_log = []),方便后续诊断setItem() 失败时,可 fallback 到 sessionStorage(生命周期更短但可用性略高),或直接走网络回传所谓“清理缓存”如果只调 localStorage.clear(),大概率漏掉真正占空间的 sessionStorage、IndexedDB 实例,甚至 Service Worker 缓存。用户点击“清除本地数据”按钮时,预期是彻底清空,不是半残。
立即学习“前端免费学习笔记(深入)”;
localStorage.clear() → sessionStorage.clear() → indexedDB.databases().then(dbs => dbs.forEach(db => indexedDB.deleteDatabase(db.name)))
caches.keys().then(keys => Promise.all(keys.map(key => caches.delete(key))))
function clearAllStorage() {
localStorage.clear();
sessionStorage.clear();
if ('indexedDB' in window) {
indexedDB.databases().then(dbs => {
dbs.forEach(db => indexedDB.deleteDatabase(db.name));
});
}
if ('caches' in window) {
caches.keys().then(keys => {
keys.forEach(key => caches.delete(key));
});
}
}
localStorage 的边界从来不在“能不能存”,而在“什么时候不该存”。真正容易被忽略的是:它没有过期机制、不支持异步、无法监听容量变化——这些限制决定了它只适合存小而稳的键值对,而不是当数据库用。