元素码农
基础
UML建模
数据结构
算法
设计模式
网络
TCP/IP协议
HTTPS安全机制
WebSocket实时通信
数据库
sqlite
postgresql
clickhouse
后端
rust
go
java
php
mysql
redis
mongodb
etcd
nats
zincsearch
前端
浏览器
javascript
typescript
vue3
react
游戏
unity
unreal
C++
C#
Lua
App
android
ios
flutter
react-native
安全
Web安全
测试
软件测试
自动化测试 - Playwright
人工智能
Python
langChain
langGraph
运维
linux
docker
工具
git
svn
🌞
🌙
目录
▶
浏览器架构概览
多进程架构设计
浏览器内核组成
进程间通信机制
沙箱安全机制
浏览器加载页面流程
▶
渲染引擎原理
HTML解析算法
CSSOM构建过程
布局计算原理
图层合成机制
重绘与回流优化
▶
JavaScript引擎
V8执行流水线
事件循环机制
内存管理策略
JIT编译原理
垃圾回收算法
▶
网络栈实现
HTTP协议栈
缓存机制详解
资源加载策略
WebSocket实现
网络安全机制
▶
浏览器存储
Cookie管理机制
Web Storage实现
IndexedDB原理
缓存存储策略
▶
浏览器安全
同源策略实现
发布时间:
2025-03-23 15:41
↑
☰
# 浏览器缓存机制详解 ## 概述 浏览器缓存是提升Web应用性能的关键机制,通过合理利用缓存可以减少网络请求、加快页面加载速度。本文将详细介绍浏览器缓存的工作原理和最佳实践。 ## 缓存类型 ### 1. HTTP缓存 #### 强缓存 ```http # 过期时间控制 Cache-Control: max-age=3600 Expires: Wed, 21 Oct 2023 07:28:00 GMT ``` #### 协商缓存 ```http # 最后修改时间 Last-Modified: Wed, 21 Oct 2023 07:28:00 GMT If-Modified-Since: Wed, 21 Oct 2023 07:28:00 GMT # ETag标识 ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4" If-None-Match: "33a64df551425fcc55e4d42a148795d9f25f89d4" ``` ### 2. 浏览器存储 #### Memory Cache ```javascript // 内存缓存示例 const img = new Image(); img.src = 'large-image.jpg'; document.body.appendChild(img); // 再次使用相同图片时会从内存缓存加载 const img2 = new Image(); img2.src = 'large-image.jpg'; ``` #### Disk Cache ```javascript // 磁盘缓存配置 const response = await fetch('api/data', { headers: { 'Cache-Control': 'public, max-age=31536000' } }); ``` ## 缓存策略 ### 1. 资源类型策略 #### HTML文档 ```http # 动态HTML需要及时更新 Cache-Control: no-cache ETag: "abc123" ``` #### 静态资源 ```http # 长期缓存带版本号的静态资源 Cache-Control: public, max-age=31536000, immutable ``` ### 2. 版本控制 #### 文件名Hash ```javascript // Webpack配置示例 module.exports = { output: { filename: '[name].[contenthash].js', chunkFilename: '[name].[contenthash].chunk.js' } }; ``` #### 查询参数 ```html <!-- 通过查询参数控制版本 --> <link rel="stylesheet" href="styles.css?v=1.2.3"> <script src="app.js?v=1.2.3"></script> ``` ## 缓存控制 ### 1. Cache-Control #### 指令说明 - public: 可以被任何缓存服务器缓存 - private: 只能被浏览器缓存 - no-cache: 强制验证缓存 - no-store: 禁止缓存 - max-age: 最大有效期 - s-maxage: 共享缓存有效期 #### 应用示例 ```javascript // 服务端设置缓存控制 app.get('/api/data', (req, res) => { res.set({ 'Cache-Control': 'private, max-age=3600', 'ETag': generateETag(data) }); res.json(data); }); ``` ### 2. 缓存清除 #### 强制刷新 ```javascript // 清除特定URL的缓存 async function clearUrlCache(url) { const cache = await caches.open('v1'); await cache.delete(url); } // 清除所有缓存 async function clearAllCache() { const cacheNames = await caches.keys(); await Promise.all( cacheNames.map(name => caches.delete(name)) ); } ``` #### Service Worker ```javascript // Service Worker缓存控制 self.addEventListener('fetch', event => { event.respondWith( caches.match(event.request) .then(response => { if (response) { // 检查缓存是否过期 const cacheAge = Date.now() - new Date(response.headers.get('date')); if (cacheAge < 3600000) { // 1小时内的缓存 return response; } } return fetch(event.request); }) ); }); ``` ## 性能优化 ### 1. 预缓存策略 #### Service Worker ```javascript // 安装时预缓存资源 self.addEventListener('install', event => { event.waitUntil( caches.open('static-v1').then(cache => { return cache.addAll([ '/', '/styles/main.css', '/scripts/app.js', '/images/logo.png' ]); }) ); }); ``` #### 资源提示 ```html <!-- 预加载关键资源 --> <link rel="preload" href="critical.js" as="script"> <link rel="preload" href="critical.css" as="style"> <!-- 预缓存可能需要的资源 --> <link rel="prefetch" href="non-critical.js"> ``` ### 2. 缓存优化 #### 缓存分组 ```javascript // 不同资源类型使用不同缓存策略 const cacheStrategies = { images: { name: 'image-cache', maxAge: 7 * 24 * 60 * 60, // 7天 maxEntries: 100 // 最多缓存100张图片 }, api: { name: 'api-cache', maxAge: 60 * 60, // 1小时 maxEntries: 50 } }; ``` #### 动态缓存 ```javascript // 根据资源重要性动态调整缓存策略 class CacheManager { constructor() { this.strategies = new Map(); } setStrategy(url, strategy) { const urlPattern = new URL(url).pathname; this.strategies.set(urlPattern, strategy); } async fetchWithCache(request) { const strategy = this.getStrategy(request.url); if (!strategy) return fetch(request); const cache = await caches.open(strategy.cacheName); const response = await cache.match(request); if (response) { // 验证缓存是否符合策略 if (this.isValid(response, strategy)) { return response; } } // 获取新响应并缓存 const newResponse = await fetch(request); await cache.put(request, newResponse.clone()); return newResponse; } } ``` ## 调试工具 ### 1. 开发者工具 #### Chrome DevTools - Network面板缓存状态 - Application面板存储查看 - 禁用缓存功能 #### 缓存分析 ```javascript // 缓存使用情况分析 async function analyzeCacheUsage() { const cacheNames = await caches.keys(); const usage = {}; for (const name of cacheNames) { const cache = await caches.open(name); const requests = await cache.keys(); usage[name] = { count: requests.length, size: 0 }; for (const request of requests) { const response = await cache.match(request); const blob = await response.blob(); usage[name].size += blob.size; } } return usage; } ``` ### 2. 监控指标 #### 缓存命中率 ```javascript // 缓存性能监控 class CacheMonitor { constructor() { this.stats = { hits: 0, misses: 0 }; } recordHit() { this.stats.hits++; this.updateMetrics(); } recordMiss() { this.stats.misses++; this.updateMetrics(); } getHitRate() { const total = this.stats.hits + this.stats.misses; return total > 0 ? this.stats.hits / total : 0; } updateMetrics() { // 发送指标到监控系统 console.log({ hitRate: this.getHitRate(), hits: this.stats.hits, misses: this.stats.misses }); } } ``` ## 最佳实践 ### 1. 缓存策略 - 对静态资源使用强缓存 - 对API响应使用协商缓存 - 合理设置缓存过期时间 - 使用版本化URL - 实施分级缓存策略 ### 2. 性能优化 - 预缓存关键资源 - 合理使用prefetch和preload - 实现优雅的降级策略 - 定期清理过期缓存 - 监控缓存效果