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

วิธี Redirect หน้าเว็บหลังจากเวลาที่กำหนดโดยไม่ใช้ JavaScript (ใช้ Meta Tag)

Redirect ด้วย Meta Tag (No JavaScript)

ใช้ <meta> Tag พร้อม Attribute http-equiv="refresh" เพื่อส่ง Header สั่ง Browser Redirect หลังจากเวลาที่กำหนด

รูปแบบไวยากรณ์ (Syntax)

<meta http-equiv="refresh" content="seconds; url=target_url">
  • seconds: จำนวนวินาทีก่อน Redirect (0 = ทันที)
  • url: URL ปลายทาง (ถ้าไม่ระบุจะ Refresh หน้าเดิม)

ตัวอย่างโค้ด: Redirect ไป tutorialspoint.com หลัง 2 วินาที

<!DOCTYPE html>
<html>
  <head>
    <title>Redirection</title>
    <meta http-equiv="refresh" content="2; url=https://www.tutorialspoint.com" />
  </head>
  <body>
    <p>This page will redirect in 2 seconds.</p>
  </body>
</html>

กรณีการใช้งาน (Use Cases)

  • หน้า Maintenance / Under Construction
  • ย้าย Domain / เปลี่ยน URL Structure
  • หน้า Login 成功 → Redirect ไป Dashboard
  • Countdown Page ก่อนดาวน์โหลด
  • AMP Pages (ที่ห้ามใช้ JavaScript)
  • Email HTML (Client บางตัวบล็อก JS)

ข้อดีและข้อจำกัด

แนะนำ: Server-side Redirect (301/302) ดีกว่าสำหรับ SEO

  • Apache (.htaccess): Redirect 301 /old-page /new-page
  • Nginx: rewrite ^/old-page$ /new-page permanent;
  • PHP: header("Location: /new-page", true, 301); exit;
  • Node.js (Express): res.redirect(301, "/new-page")

สรุป

ใช้ <meta http-equiv="refresh" content="seconds; url=..."> สำหรับ Redirect แบบง่าย ไม่ใช้ JavaScript เหมาะสำหรับ AMP, Email, Static Pages แต่สำหรับ Production Website ควรใช้ Server-side 301/302 Redirect เพื่อ SEO และ UX ที่ดีกว่า

ข้อดีข้อจำกัด
ทำงานได้แม้ Browser ปิด JavaScriptไม่สามารถทำ Logic ซับซ้อนได้ (เงื่อนไข, ตัวแปร)
ง่าย ไม่ต้องเขียน Scriptผู้ใช้ไม่สามารถยกเลิกได้ (Back Button อาจไม่ทำงาน)
SEO Friendly (ถ้าใช้ 301 Redirect ดีกว่า)ไม่ใช่ HTTP Redirect จริง (Client-side) SEO อาจไม่รับรู้
รองรับ Browser เก่าทุกตัวไม่ส่ง Status Code 301/302 (Browser ยังคิดว่าเป็นหน้าเดิม)