js页面实现缓存
实现页面缓存的常见方法
使用LocalStorage或SessionStorage
LocalStorage和SessionStorage是浏览器提供的Web Storage API,适合存储键值对数据。LocalStorage数据长期保留,SessionStorage在会话结束时清除。
// 存储数据
localStorage.setItem('key', 'value');
// 读取数据
const data = localStorage.getItem('key');
// 删除数据
localStorage.removeItem('key');
通过Cache API缓存资源
Cache API是Service Worker的一部分,适合缓存网络请求和静态资源。
// 开启缓存
caches.open('cache-v1').then(cache => {
cache.addAll(['/style.css', '/script.js']);
});
// 匹配缓存
caches.match('/style.css').then(response => {
if (response) console.log('资源已缓存');
});
利用IndexedDB存储结构化数据
IndexedDB适合存储大量结构化数据,支持事务和索引查询。
const request = indexedDB.open('myDatabase', 1);
request.onsuccess = (event) => {
const db = event.target.result;
const tx = db.transaction('store', 'readwrite');
tx.objectStore('store').put('value', 'key');
};
通过HTTP缓存头控制缓存
服务器可通过响应头控制缓存行为,如Cache-Control和Expires。
Cache-Control: max-age=3600
ETag: "xyz123"
使用Service Worker实现离线缓存
Service Worker可拦截网络请求,实现离线优先策略。

self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then(response => {
return response || fetch(event.request);
})
);
});
选择缓存策略的注意事项
- 数据敏感性:敏感数据避免长期缓存。
- 存储容量:LocalStorage约5MB,IndexedDB可扩展至更大。
- 缓存失效:需设置合理的更新机制或版本控制。
通过组合上述方法,可根据实际需求实现灵活的页面缓存方案。






