🚀 JavaScript的缓存机制来提高性能
欢迎来到我的博客文章!所有文章都是满满的前端干货,文章简明扼要。
🔹 一、运行时内置缓存(浏览器/Node.js 提供)
HTTP 缓存
浏览器对 script/import 的 JS 文件按 Cache-Control 等头缓存
V8 引擎优化
- 内联缓存(Inline Caching):加速属性访问
- 代码缓存(Code Caching):加快二次执行
✅ 工程建议:在 Vite + 模块联邦项目中,确保:
build: {
rollupOptions: {
output: {
entryFileNames: `[name].[hash].js`,
chunkFileNames: `[name].[hash].js`,
}
}
}
并配置 CDN 缓存策略,让 Remote 模块只更新变动部分。
🔹 二、代码级显式缓存(开发者可控)
记忆化(Memoization)—— 缓存纯函数结果
适用于:计算密集、输入可序列化的场景(如数学公式、格式转换、React 计算属性)。
function memoize(fn) {
const cache = new Map();
return (...args) => {
const key = JSON.stringify(args);
if (cache.has(key)) return cache.get(key);
const result = fn(...args);
cache.set(key, result);
return result;
};
}
const calcTax = memoize((income, rate) => {
console.log("计算中...");
return income * rate;
});
calcTax(10000, 0.1);
calcTax(10000, 0.1);
🔧 进阶优化: - 用 WeakMap + 引用作为 key(避免内存泄漏,适合缓存 DOM 节点相关计算)
- 限制缓存大小(LRU 策略),防内存爆炸
- React 中可用 useMemo / useCallback 实现组件级记忆化
请求级缓存(前端 API 层)
在 fetch 封装层中加入缓存:
const apiCache = new Map<string, { data: any; expires: number }>();
async function cachedFetch(url: string, ttl = 5 * 60 * 1000) {
const now = Date.now();
const cached = apiCache.get(url);
if (cached && cached.expires > now) {
return cached.data;
}
const res = await fetch(url);
const data = await res.json();
apiCache.set(url, { data, expires: now + ttl });
return data;
}
💡 搭配建议:配合 SWR / React Query 等库,可实现自动 stale-while-revalidate 策略。
🔹 三、构建时缓存(工程化加速)
主要优化点:
- 依赖缓存:复用 .vite + node_modules 缓存
- CI 缓存策略:缓存构建产物和依赖
- pnpm store:全局依赖存储,避免重复下载
- 增量构建:只构建变更的模块
🔹 四、持久化缓存(用户设备级)
当页面刷新后仍需保留缓存时使用:
| 方案 | 容量 | 生命周期 | 适用场景 |
| localStorage | ~5MB | 永久(除非清除) | 用户偏好、低频配置 |
| sessionStorage | ~5MB | 会话级 | 临时表单数据 |
| IndexedDB | ~50% 磁盘空间 | 永久 | 大量结构化数据(如离线文档、缓存 API 响应) |
| Cache API(Service Worker) | 大 | 可编程控制 | PWA 资源缓存、离线 fallback |
✅ 综合建议(前端组长视角)
| 场景 | 推荐缓存策略 | 工具/库 |
| 频繁计算(数学/格式) | 记忆化(memoize) | 自研 / lodash.memoize |
| 远程模块加载 | 模块缓存 + eager 共享 | Webpack Module Federation |
| API 请求 | 内存缓存 + SWR 策略 | swr, react-query, axios-cache-interceptor |
| 构建速度 | 复用 .vite + node_modules 缓存 | CI 缓存策略、pnpm store |
| 离线体验 | Service Worker + Cache API | Workbox |
| 大型状态 | useMemo + useCallback + 持久化插件 | Zustand/Pinia 持久化插件 |