針對靜態資源(CSS、JS、圖片)的瀏覽器快取,提供三層次解決方案:版本號參數、AJAX 強制重新驗證、jQuery 內建快取控制。
<script src="app.js?v=20240115"></script>
<link rel="stylesheet" href="style.css?v=1.2.3" />
preventCache: true 會自動加亂數參數 _=timestamp。If-Modified-Since: 0 與 Cache-Control: no-cache$.ajax({
url: "static/cache.js",
dataType: "text",
beforeSend: function(xhr) {
xhr.setRequestHeader("If-Modified-Since", "0");
xhr.setRequestHeader("Cache-Control", "no-cache");
}
});
強制瀏覽器向伺服器驗證,若資源未變更回傳 304 Not Modified,否則取得新內容並更新快取。
$.ajax({
url: "static/cache.js",
dataType: "text",
cache: false, // 自動加 _=timestamp 參數
ifModified: true // 搭配 Last-Modified 頭部
});
Expires/Cache-Control: max-age=... 利用快取減輕頻寬。Last-Modified / ETag 支援條件請求。