缓存策略的核心是控制请求是否发出,JavaScript通过Map内存缓存、fetch自定义cache模式及localStorage持久化实现业务级缓存,需结合过期机制与缓存键设计。
JavaScript 本身不提供全局缓存机制,所谓“JS 缓存策略”,本质是开发者在 fetch 或 XMLHttpRequest 发起前,主动判断:这个数据我有没有、还新不新?该不该跳过网络请求?浏览器的 HTTP 缓存(如 Cache-Control)由服务端控制,JS 层能做的,是补充它做不到的事——比如按业务逻辑缓存用户偏好、临时 token、列表页筛选结果等。
适合短期、单页生命周期内的数据复用,比如搜索建议、用户资料快照。不用引入第三方库,几行就能落地:
const memoryCache = new Map();function getCachedData(key) { const item = memoryCache.get(key); if (!item) return null; if (Date.now() - item.timestamp > 5 60 1000) { // 5 分钟过期 memoryCache.delete(key); return null; } return item.value; }
function setCachedData(key, value) { memoryCache.set(key, { value, timestamp: Date.now() }); }
Map 比 Object 更适合做缓存键(支持任意类型 key,包括对象引用)max-age
Map 清空,这不是 bug,是预期行为;要持久化请用 localStorage 或 indexedDB
浏览器原生 fetch 支持 cache 选项,但默认只响应服务端设置的 Cache-Control。想绕过它、强制走 JS 控制逻辑,就得禁用浏览器缓存:
cache: 'no-store':每次请求都发出去,JS 自己决定要不要用缓存值cache: 'only-if-cached':仅从 HTTP 缓存取,失败直接 reject(需配合 credentials: 'same-origin' 等限制)cacheKey
示例中避免重复请求同一用户资料:
const userCache = new Map();async function fetchUser(userId) { const cacheKey =
user:${userId}; const cached = getCachedData(cacheKey); if (cached) return cached;const res = await fetch(
/api/users/${userId}, { cache: 'no-store' // 不让浏览器插手 }); const data = await res.json(); setCachedData(cacheKey, data); return data; }
适合保存用户设置、离线可用的静态资源路径等低频更新数据。但别把它当数据库用:
localStorage.setItem() 只接受字符串,必须用 JSON.stringify(),取回时要 JSON.parse(),失败会静默抛错QuotaExceededError
http://a.com 和 https://a.com 是两个独立空间expires 字段并每次读取时校验简单封装防崩:
function safeSetItem(key, value) {
try {
localStorage.setItem(key, JSON.stringify({
value,
expires: Date.now() + 24 * 60 * 60 * 1000 // 24 小时后过期
}));
} catch (e) {
console.warn('localStorage full or blocked:', e);
}
}
function safeGetItem(key) {
try {
const item = localStorage.getItem(key);
if (!item) return null;
const parsed = JSON.parse(item);
if (parsed.expires && Date.now() > parsed.expires) {
localStorage.removeItem(key);
return null;
}
return parsed.value;
} catch (e) {
console.warn('JSON parse failed
for', key, e);
return null;
}
}
真正难的不是写几行缓存代码,而是判断哪些数据值得缓、缓多久、失效时怎么通知 UI 更新——这些都得贴着业务来定,没有通用解。