前端缓存策略:让你的网站飞起来

张开发
2026/4/3 20:25:25 15 分钟阅读
前端缓存策略:让你的网站飞起来
前端缓存策略让你的网站飞起来毒舌时刻前端缓存这不是浏览器的事吗我不需要管缓存浏览器会自动处理——结果网站加载慢用户体验差缓存就是localStorage嘛多简单——结果缓存管理混乱内存占用高我直接禁用缓存省得麻烦——结果每次都重新加载浪费带宽。醒醒吧前端缓存不是简单的localStorage而是一套完整的策略为什么你需要这个性能提升减少重复请求加快页面加载速度用户体验离线访问减少等待时间带宽节省减少服务器流量降低成本可靠性网络不稳定时仍能正常访问反面教材// 反面教材滥用localStorage function fetchData() { // 每次都从API获取数据 return fetch(https://api.example.com/data) .then(res res.json()) .then(data { // 直接存储到localStorage localStorage.setItem(data, JSON.stringify(data)); return data; }); } // 反面教材没有缓存失效策略 function getCachedData() { // 永远使用缓存不考虑过期 const cachedData localStorage.getItem(data); return cachedData ? JSON.parse(cachedData) : null; } // 反面教材缓存键命名混乱 function cacheData(key, data) { // 缓存键没有统一规范 localStorage.setItem(cache_${key}_${Date.now()}, JSON.stringify(data)); }正确的做法// 正确的做法完整的缓存策略 class CacheManager { constructor() { this.cachePrefix app_cache_; this.defaultExpiry 24 * 60 * 60 * 1000; // 24小时 } // 生成缓存键 generateKey(key) { return ${this.cachePrefix}${key}; } // 存储数据到缓存 set(key, data, expiry this.defaultExpiry) { const cacheItem { data, expiry: Date.now() expiry, timestamp: Date.now() }; try { localStorage.setItem(this.generateKey(key), JSON.stringify(cacheItem)); } catch (error) { console.error(Cache storage error:, error); // 处理存储空间不足的情况 this.clearOldCache(); } } // 从缓存获取数据 get(key) { const cacheItem localStorage.getItem(this.generateKey(key)); if (!cacheItem) { return null; } try { const parsedItem JSON.parse(cacheItem); // 检查是否过期 if (Date.now() parsedItem.expiry) { this.remove(key); return null; } return parsedItem.data; } catch (error) { console.error(Cache parsing error:, error); this.remove(key); return null; } } // 移除缓存 remove(key) { localStorage.removeItem(this.generateKey(key)); } // 清空所有缓存 clear() { Object.keys(localStorage).forEach(key { if (key.startsWith(this.cachePrefix)) { localStorage.removeItem(key); } }); } // 清理过期缓存 clearOldCache() { Object.keys(localStorage).forEach(key { if (key.startsWith(this.cachePrefix)) { try { const item JSON.parse(localStorage.getItem(key)); if (Date.now() item.expiry) { localStorage.removeItem(key); } } catch (error) { localStorage.removeItem(key); } } }); } // 获取缓存大小 getCacheSize() { let size 0; Object.keys(localStorage).forEach(key { if (key.startsWith(this.cachePrefix)) { size localStorage.getItem(key).length; } }); return size; } } // 正确的做法使用Service Worker缓存 // service-worker.js const CACHE_NAME app-cache-v1; const ASSETS_TO_CACHE [ /, /index.html, /manifest.json, /static/js/main.js, /static/css/main.css, /static/images/logo.png ]; // 安装Service Worker self.addEventListener(install, event { event.waitUntil( caches.open(CACHE_NAME) .then(cache { console.log(Opened cache); return cache.addAll(ASSETS_TO_CACHE); }) ); }); // 激活Service Worker self.addEventListener(activate, event { const cacheWhitelist [CACHE_NAME]; event.waitUntil( caches.keys().then(cacheNames { return Promise.all( cacheNames.map(cacheName { if (cacheWhitelist.indexOf(cacheName) -1) { return caches.delete(cacheName); } }) ); }) ); }); // 拦截网络请求 self.addEventListener(fetch, event { event.respondWith( caches.match(event.request) .then(response { // 如果缓存中有响应直接返回 if (response) { return response; } // 否则发起网络请求 return fetch(event.request) .then(response { // 如果响应有效缓存一份 if (response response.status 200 response.type basic) { const responseToCache response.clone(); caches.open(CACHE_NAME) .then(cache { cache.put(event.request, responseToCache); }); } return response; }); }) ); }); // 正确的做法API请求缓存 async function fetchWithCache(url, options {}) { const cacheKey api_${url}_${JSON.stringify(options)}; const cacheManager new CacheManager(); // 尝试从缓存获取 const cachedData cacheManager.get(cacheKey); if (cachedData) { return cachedData; } // 发起网络请求 const response await fetch(url, options); const data await response.json(); // 缓存数据 cacheManager.set(cacheKey, data, 5 * 60 * 1000); // 5分钟过期 return data; }毒舌点评看看这才叫前端缓存策略不是简单地使用localStorage而是构建一套完整的缓存管理系统包括过期策略、空间管理、Service Worker等。记住缓存不是越多越好而是要合理使用。你需要根据数据的性质和使用频率选择合适的缓存策略。所以别再觉得缓存是浏览器的事了它是前端性能优化的重要组成部分总结localStorage适合存储小量、不敏感的数据sessionStorage适合存储会话期间的数据IndexedDB适合存储大量结构化数据Service Worker适合缓存静态资源和API响应缓存策略合理设置过期时间定期清理过期缓存缓存键管理使用统一的命名规范避免缓存键冲突错误处理处理存储空间不足等异常情况性能监控监控缓存命中率不断优化缓存策略前端缓存让你的网站飞起来

更多文章