元素码农
基础
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 16:03
↑
☰
# 浏览器缓存存储策略 ## 概述 浏览器缓存存储策略是前端性能优化的重要组成部分。本文将详细介绍浏览器缓存的工作原理、存储机制以及最佳实践方案。 ## 基本概念 ### 1. 缓存类型 #### HTTP缓存 ```javascript // HTTP缓存控制 class HTTPCache { constructor() { this.cacheControl = { 'max-age': 3600, 'must-revalidate': true, 'no-cache': false, 'no-store': false }; } setCacheControl(response) { const headers = []; if (this.cacheControl['max-age']) { headers.push(`max-age=${this.cacheControl['max-age']}`); } if (this.cacheControl['must-revalidate']) { headers.push('must-revalidate'); } if (this.cacheControl['no-cache']) { headers.push('no-cache'); } if (this.cacheControl['no-store']) { headers.push('no-store'); } response.setHeader('Cache-Control', headers.join(', ')); } setETag(response, resource) { const hash = this.generateHash(resource); response.setHeader('ETag', `"${hash}"`); } setLastModified(response, timestamp) { response.setHeader( 'Last-Modified', new Date(timestamp).toUTCString() ); } generateHash(resource) { // 简单的哈希生成 return Buffer.from(JSON.stringify(resource)) .toString('base64') .substring(0, 27); } } ``` #### 浏览器缓存 ```javascript // 浏览器缓存管理 class BrowserCache { constructor() { this.memoryCache = new Map(); this.diskCache = new Map(); } async get(key, options = {}) { // 优先从内存缓存获取 if (this.memoryCache.has(key)) { const entry = this.memoryCache.get(key); if (!this.isExpired(entry)) { return entry.value; } this.memoryCache.delete(key); } // 从磁盘缓存获取 if (this.diskCache.has(key)) { const entry = this.diskCache.get(key); if (!this.isExpired(entry)) { // 提升到内存缓存 this.memoryCache.set(key, entry); return entry.value; } this.diskCache.delete(key); } return null; } set(key, value, options = {}) { const entry = { value, timestamp: Date.now(), expires: options.expires || 3600000, // 默认1小时 maxAge: options.maxAge }; // 存储到内存缓存 this.memoryCache.set(key, entry); // 持久化到磁盘缓存 if (options.persist) { this.diskCache.set(key, entry); } } isExpired(entry) { const now = Date.now(); // 检查过期时间 if (entry.expires && now >= entry.timestamp + entry.expires) { return true; } // 检查最大存活时间 if (entry.maxAge && now >= entry.timestamp + entry.maxAge) { return true; } return false; } } ``` ### 2. 缓存策略 #### 强缓存 ```javascript // 强缓存实现 class StrongCache { constructor() { this.cache = new Map(); } setCacheHeaders(response) { // Cache-Control策略 response.setHeader('Cache-Control', 'max-age=31536000'); // 1年 // 兼容Expires const expires = new Date(); expires.setFullYear(expires.getFullYear() + 1); response.setHeader('Expires', expires.toUTCString()); } shouldUseCache(request) { const url = request.url; const extension = url.split('.').pop().toLowerCase(); // 静态资源使用强缓存 const staticTypes = ['jpg', 'png', 'gif', 'css', 'js']; return staticTypes.includes(extension); } async handleRequest(request, response) { if (this.shouldUseCache(request)) { this.setCacheHeaders(response); } } } ``` #### 协商缓存 ```javascript // 协商缓存实现 class NegotiateCache { constructor() { this.resources = new Map(); } async handleRequest(request, response) { const url = request.url; const resource = this.resources.get(url); if (!resource) { return false; } // ETag验证 const ifNoneMatch = request.headers['if-none-match']; if (ifNoneMatch && ifNoneMatch === resource.etag) { response.statusCode = 304; return true; } // Last-Modified验证 const ifModifiedSince = request.headers['if-modified-since']; if (ifModifiedSince && new Date(ifModifiedSince) >= new Date(resource.lastModified)) { response.statusCode = 304; return true; } return false; } updateResource(url, content) { this.resources.set(url, { content, etag: this.generateETag(content), lastModified: new Date().toUTCString() }); } generateETag(content) { return `W/"${Buffer.from(content).toString('base64')}"`; } } ``` ## 实现机制 ### 1. 缓存控制 #### 缓存决策 ```javascript // 缓存决策器 class CacheDecision { constructor() { this.rules = []; } addRule(pattern, strategy) { this.rules.push({ pattern, strategy }); } async decide(request) { const url = request.url; for (const rule of this.rules) { if (rule.pattern.test(url)) { return rule.strategy; } } return 'no-cache'; // 默认不缓存 } // 配置示例 static getDefaultRules() { const decision = new CacheDecision(); // 静态资源使用强缓存 decision.addRule( /\.(jpg|jpeg|png|gif|ico|css|js)$/i, 'strong' ); // API响应使用协商缓存 decision.addRule( /\/api\//i, 'negotiate' ); // HTML使用协商缓存 decision.addRule( /\.html$/i, 'negotiate' ); return decision; } } ``` #### 缓存验证 ```javascript // 缓存验证器 class CacheValidator { constructor() { this.validators = new Map(); } addValidator(key, validator) { this.validators.set(key, validator); } async validate(key, request, cachedResponse) { const validator = this.validators.get(key); if (!validator) { return false; } return await validator(request, cachedResponse); } // 验证器示例 static getDefaultValidators() { const validator = new CacheValidator(); // ETag验证 validator.addValidator('etag', (request, cached) => { return request.headers['if-none-match'] === cached.headers['etag']; }); // Last-Modified验证 validator.addValidator('lastModified', (request, cached) => { const ifModifiedSince = new Date(request.headers['if-modified-since']); const lastModified = new Date(cached.headers['last-modified']); return ifModifiedSince >= lastModified; }); return validator; } } ``` ### 2. 存储管理 #### 存储引擎 ```javascript // 缓存存储引擎 class CacheStorage { constructor() { this.stores = new Map(); } addStore(name, store) { this.stores.set(name, store); } async get(name, key) { const store = this.stores.get(name); if (!store) { return null; } return await store.get(key); } async set(name, key, value, options = {}) { const store = this.stores.get(name); if (!store) { return false; } return await store.set(key, value, options); } // 存储引擎示例 static getDefaultStores() { const storage = new CacheStorage(); // 内存存储 storage.addStore('memory', new MemoryStore()); // IndexedDB存储 storage.addStore('indexeddb', new IndexedDBStore()); // 文件系统存储 storage.addStore('filesystem', new FileSystemStore()); return storage; } } ``` #### 清理策略 ```javascript // 缓存清理器 class CacheCleaner { constructor(storage) { this.storage = storage; this.policies = new Map(); } addPolicy(name, policy) { this.policies.set(name, policy); } async clean() { for (const [name, policy] of this.policies) { await policy.execute(this.storage); } } // 清理策略示例 static getDefaultPolicies() { const cleaner = new CacheCleaner(); // LRU策略 cleaner.addPolicy('lru', new LRUPolicy({ maxSize: 100 * 1024 * 1024, // 100MB maxAge: 7 * 24 * 60 * 60 * 1000 // 7天 })); // 过期清理策略 cleaner.addPolicy('expired', new ExpiredPolicy()); // 容量控制策略 cleaner.addPolicy('quota', new QuotaPolicy({ maxSize: 500 * 1024 * 1024 // 500MB })); return cleaner; } } ```