瀏覽器對靜態資源(圖片、CSS、JS)積極緩存。同一 URL 再次請求時直接讀取緩存,導致服務端圖片更新後前端仍顯示舊版。
在圖片 URL 後添加唯一查詢參數,強制瀏覽器視為新資源發起請求。
// 適用於極少數「必須實時」場景
img.src = `https://example.com/avatar.jpg?t=${Date.now()}`;
// 或
img.src = `https://example.com/avatar.jpg?v=${new Date().getTime()}`;
// 構建工具自動注入 hash
img.src = `https://example.com/avatar.jpg?v=abc123def`;
// 或路徑級 hash
img.src = `https://example.com/avatar.abc123def.jpg`;
構建工具配置示例:
output.filename: '[name].[contenthash].js'import.meta.glob + hashgulp-rev / grunt-rev服務端正確設置 Cache-Control、ETag、Last-Modified,瀏覽器自動協商緩存,無需前端干預。
# Nginx 示例
location ~* \.(jpg|jpeg|png|gif|webp)$ {
expires 1y;
add_header Cache-Control "public";
etag on;
}
// jQuery
$('.myImg').attr('src', 'yourUrl.action?rand=' + Date.now());
// Vue 3 組合式
const imgSrc = ref('avatar.jpg?v=' + import.meta.env.VITE_APP_VERSION);
// React
// Axios 請求攔截器添加時間戳(僅用於 API,圖片通常直接
)
axios.interceptors.request.use(config => {
if (config.url.includes('/api/')) config.params = { ...config.params, _t: Date.now() };
return config;
});