Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách bắt buộc client làm mới (refresh) file JavaScript (cache busting)?

Khi cập nhật file JS, trình duyệt có thể vẫn dùng bản cache cũ. Cần cache busting để buộc tải file mới.

Cách 1: Thêm query string version vào src (Phổ biến nhất)

<script src="myfile.js?v=1.2.3"></script>
<!-- Hoặc timestamp -->
<script src="myfile.js?t=1705312200"></script>

Mỗi lần deploy, cập nhật version/timestamp → trình duyệt coi là URL mới → tải lại.

Cách 2: Đổi tên file (Content Hash - Khuyến nghị production)

<script src="myfile.a1b2c3d4.js"></script>

Build tools (Webpack, Vite, Rollup, Parcel) tự động thêm hash nội dung vào tên file. Nội dung thay đổi → hash thay đổi → cache tự động vô hiệu.

Cách 3: Cấu hình HTTP Headers (Server-side)

File .htaccess (Apache):

# Cache 1 năm cho file tĩnh có hash
<FilesMatch "\.(js|css|png|jpg|woff2)$">
    Header set Cache-Control "max-age=31536000, immutable"
</FilesMatch>

# Không cache HTML
<FilesMatch "\.html$">
    Header set Cache-Control "no-cache, must-revalidate"
</FilesMatch>

Nginx:

location ~* \.(js|css|png|jpg|woff2)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
}

Cách 4: Meta tag (Không khuyến khích cho JS)

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">

Chỉ ảnh hưởng HTML, không kiểm soát được cache JS/CSS riêng lẻ.

Tóm tắt chiến lược:

Môi trườngCách khuyến nghị
DevelopmentDisable cache trong DevTools (Network tab)
Production (có build tool)Content hash trong tên file (auto)
Production (manual)Query string ?v=version
Tất cảCấu hình Cache-Control header phù hợp