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

วิธีใช้ Meta Tag เปลี่ยนเส้นทางหน้า HTML (Meta Refresh Redirect)

Page redirection คือ คลิก URL หน้า X แต่ถูกนำไปหน้า Y ใช้ META Tag เปลี่ยนเส้นทางได้ง่าย

ใช้แอตทริบิวต์ http-equiv="refresh" เพื่อให้ HTTP header สำหรับค่า content attribute

ตัวอย่าง: Redirect หลัง 2 วินาที

<!DOCTYPE html> <html>
  <head>
    <title>HTML Meta Tag</title>
    <meta http-equiv="refresh" content="2; url=https://www.tutorialspoint.com" />
  </head>
  <body>
    <p>This is demo text.</p>
  </body>
</html>

รูปแบบ content attribute

content="seconds; url=target_url"
  • seconds – จำนวนวินาทีก่อน redirect (0 = ทันที)
  • url – URL ปลายทาง

ข้อควรระวัง

  • UX แย่: ผู้ใช้อาจสับสนหรือระคายเคือง
  • SEO ติดลบ: Google ไม่ชอบ meta refresh (ถือว่า low quality) ควรใช้ HTTP 301/302 Redirect แทน
  • Accessibility: ผู้ใช้ screen reader อาจหลงทาง
  • W3C: ไม่แนะนำให้ใช้ (obsolete feature)

เมื่อไหร่ควรใช้?

  • หน้า maintenance ชั่วคราว
  • หน้า "You are being redirected..." พร้อมลิงก์ manual fallback
  • ไม่สามารถควบคุม server-side headers ได้ (เช่น static hosting บางที่)