Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีบังคับให้ Client รีเฟรชไฟล์ JavaScript (Cache Busting)

เพื่อบังคับให้ client โหลดไฟล์ JavaScript ใหม่ (ไม่ใช้ cache เก่า) ให้แก้ไขลิงก์ src ของแท็ก script

วิธีที่ 1: Query String Versioning (Cache Busting)

เพิ่ม query parameter ใน src:

<script src="myfile.js?v=1500"></script>

เปลี่ยนหมายเลขเวอร์ชันทุกครั้งที่อัปเดตไฟล์ (เช่น v=1501, v=1502) เบราว์เซอร์จะถือว่าเป็นไฟล์ใหม่และดาวน์โหลดใหม่

วิธีที่ 2: Filename Versioning (แนะนำมากกว่า)

เปลี่ยนชื่อไฟล์รวมเวอร์ชัน/แฮช:

<script src="myfile.v2.js"></script>
<script src="myfile.abc123.js"></script> <!-- content hash -->

วิธีนี้ดีกว่าเพราะ proxy servers บางตัวไม่แคช query strings

วิธีที่ 3: .htaccess (Apache) – Force Revalidation

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} \.(js|css|png|jpg|gif)$ [NC]
RewriteCond %{QUERY_STRING} !v=\d+
RewriteRule ^(.*)$ $1?v=20240115 [R=301,L]

วิธีที่ 4: HTTP Headers (Server Config)

# Apache (.htaccess)

  Header set Cache-Control "max-age=31536000, public, must-revalidate"


# หรือสำหรับ development: ไม่แคชเลย
Header set Cache-Control "no-cache, no-store, must-revalidate"

Best Practice สรุป

  1. Production: ใช้ Filename versioning/hash (webpack, vite, parcel ทำให้อัตโนมัติ)
  2. Development: ใช้ Cache-Control: no-cache หรือ DevTools "Disable cache"
  3. CDN: ตั้ง Cache-Control header ให้เหมาะสม + versioned filenames