前端缓存策略:让你的网站飞起来
前端缓存策略:让你的网站飞起来
毒舌时刻
前端缓存?这不是浏览器的事吗?
"我不需要管缓存,浏览器会自动处理"——结果网站加载慢,用户体验差,
"缓存就是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响应
- 缓存策略:合理设置过期时间,定期清理过期缓存
- 缓存键管理:使用统一的命名规范,避免缓存键冲突
- 错误处理:处理存储空间不足等异常情况
- 性能监控:监控缓存命中率,不断优化缓存策略
前端缓存,让你的网站飞起来!