js请求避免缓存的三种方式
要确保每次请求都获取最新的资源,而不是从浏览器缓存中读取旧的版本,可以采取以下几种方式:
方法一:在 URL 上添加随机查询参数(推荐)
这是最简单有效的方式之一。通过为请求的 URL 添加一个随机参数(如时间戳或随机字符串),可以绕过浏览器缓存。
export async function fetchRemoteJSAsText(url) {try {// 添加时间戳参数避免缓存const cacheBusterUrl = `${url}${url.includes('?') ? '&' : '?'}t=${Date.now()}`;const response = await fetch(cacheBusterUrl);if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}const text = await response.text();return text;} catch (error) {showFailToast('网络不良,请重试');return null;}
}
方法二:设置 Cache-Control 和 Pragma 请求头
也可以通过设置请求头来告诉浏览器不要使用缓存:
// ... existing code ...
export async function fetchRemoteJSAsText(url) {try {const response = await fetch(url, {headers: {'Cache-Control': 'no-cache, no-store, must-revalidate',Pragma: 'no-cache',Expires: '0'}});if (!response.ok) {throw new Error(`HTTP error! status: ${response.status}`);}const text = await response.text();return text;} catch (error) {showFailToast('网络不良,请重试');return null;}
}
⚠️ 注意:某些 CDN 或服务器可能会忽略这些请求头,因此建议结合 方法一 使用。
方法三:服务器端配置(最佳实践)
如果可以控制目标服务器,可以在响应头中加入以下内容,强制浏览器不缓存该资源:
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0
总结
- 如果无法修改服务器配置,推荐使用 方法一(加随机参数)。
- 如果你有权限控制服务器行为,方法三(服务端禁用缓存) 是最彻底的做法。
- 方法二(设置请求头) 在大多数情况下也有效,但可能受服务器配置影响。
- 可以选择其中一种或组合使用以确保每次都获取最新内容。