前端缓存接口数据

时间:2025-03-17 16:48:29

在前端缓存接口数据时,可以结合 浏览器缓存策略、前端存储(localStorage、sessionStorage、IndexedDB)、内存缓存(变量存储)、Service Worker 等方式,选择适合的方案。


  1. 使用浏览器 HTTP 缓存(推荐,依赖后端支持)

如果接口数据不会频繁变化,可以使用 HTTP 缓存策略(强缓存 + 协商缓存),减少不必要的请求。

后端设置 Cache-Control

在接口响应头中,服务器可以设置缓存策略:

Cache-Control: max-age=600, public
ETag: “abc123”
Last-Modified: Wed, 20 Mar 2025 10:00:00 GMT

max-age=600:缓存 10 分钟,期间不会请求服务器。

ETag 和 Last-Modified:客户端在缓存过期后,会通过 If-None-Match 或 If-Modified-Since 进行 协商缓存。

前端请求接口

fetch(’/api/data’)
.then(response => response.json())
.then(data => console.log(data));

适用场景:

数据变化不频繁的 API(如新闻、天气、配置信息)。

依赖服务器缓存策略的前端应用。


  1. 前端存储(localStorage / sessionStorage / IndexedDB)

如果数据需要在 浏览器端长时间存储,可以使用 localStorage 或 IndexedDB。

localStorage 方案

// 缓存 API 数据
async function fetchData() {
const cacheKey = ‘api_data’;
const cacheTimeKey = ‘api_data_timestamp’;
const cacheTimeLimit = 10 * 60 * 1000; // 10 分钟

const cachedData = localStorage.getItem(cacheKey);
const cacheTimestamp = localStorage.getItem(cacheTimeKey);

// 如果缓存存在且未过期,直接使用
if (cachedData && cacheTimestamp && Date.now() - cacheTimestamp < cacheTimeLimit) {
return JSON.parse(cachedData);
}

// 否则,重新请求数据
const response = await fetch(’/api/data’);
const data = await response.json();

// 存储新数据
localStorage.setItem(cacheKey, JSON.stringify(data));
localStorage.setItem(cacheTimeKey, Date.now());

return data;
}

fetchData().then(data => console.log(data));

适用场景:

缓存数据一段时间,减少 API 调用。

适用于用户配置、城市信息、字典数据等相对静态的数据。

IndexedDB 方案(适用于大数据量存储)

async function saveDataToIndexedDB(data) {
const db = await idb.openDB(‘myDatabase’, 1, {
upgrade(db) {
db.createObjectStore(‘apiData’);
},
});
await db.put(‘apiData’, data, ‘cachedData’);
}

async function getDataFromIndexedDB() {
const db = await idb.openDB(‘myDatabase’, 1);
return db.get(‘apiData’, ‘cachedData’);
}

适用场景:

大数据存储(如离线数据同步),比 localStorage 性能更好。

PWA 或离线模式。


  1. 内存缓存(适用于单页面应用)

在 Vue / React / Angular 项目中,可以用 全局变量、Vuex / Pinia / Redux / Zustand 缓存数据,避免重复请求 API。

const cache = new Map();

async function fetchWithMemoryCache(url) {
if (cache.has(url)) {
return cache.get(url);
}

const response = await fetch(url);
const data = await response.json();
cache.set(url, data);
return data;
}

适用场景:

应用生命周期内需要频繁访问的 API(如用户信息、系统设置)。

适用于单页应用(SPA),页面刷新后缓存会丢失。


  1. Service Worker(离线缓存 + 适用于 PWA)

Service Worker 可以拦截网络请求,实现 离线缓存 和 智能更新。

self.addEventListener(‘fetch’, event => {
event.respondWith(
caches.match(event.request).then(cachedResponse => {
if (cachedResponse) {
return cachedResponse;
}
return fetch(event.request).then(response => {
return caches.open(‘api-cache’).then(cache => {
cache.put(event.request, response.clone());
return response;
});
});
})
);
});

适用场景:

PWA(渐进式 Web 应用),实现离线模式。

缓存 API 请求,提高性能。


  1. 结合多种缓存策略

可以结合 不同缓存方式 来优化 API 调用,例如:

  1. 短时间内用内存缓存(提升性能)。

  2. 较长时间用 localStorage 或 IndexedDB(防止丢失)。

  3. 服务器控制 Cache-Control 进行 HTTP 缓存(减少请求)。

  4. PWA 使用 Service Worker(实现离线模式)。

示例:组合缓存策略

async function fetchDataWithCaching(url) {
// 1. 先从内存缓存获取
if (cache.has(url)) {
return cache.get(url);
}

// 2. 再从 localStorage 获取
const cachedData = localStorage.getItem(url);
if (cachedData) {
return JSON.parse(cachedData);
}

// 3. 最后请求 API
const response = await fetch(url, { cache: ‘force-cache’ });
const data = await response.json();

// 4. 更新缓存
cache.set(url, data);
localStorage.setItem(url, JSON.stringify(data));

return data;
}

适用场景:

优化性能,减少 API 调用。

适用于数据变化不频繁的场景。


总结

最佳实践:

短时间缓存(几分钟):内存(变量、Vuex、Redux)。

页面刷新后仍需要缓存:localStorage / IndexedDB。

减少 API 请求:HTTP 缓存 (Cache-Control, ETag)。

PWA 离线支持:Service Worker。

选择合适的缓存方式可以大幅提升前端性能,减少 API 负担,让页面加载更快!