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

รันสคริปต์เมื่อผู้ใช้นำทางไปยังหน้าเว็บด้วย onpageshow

เหตุการณ์ onpageshow ทำงานเมื่อผู้ใช้นำทางไปยังหน้าเว็บ รวมถึงกรณีโหลดครั้งแรก และกรณีกลับมาจากหน้าอื่น (back/forward cache - bfcache) ซึ่งแตกต่างจาก onload ที่ไม่ทำงานเมื่อโหลดจาก cache

ความแตกต่างระหว่าง onload และ onpageshow

เหตุการณ์ ทำงานเมื่อโหลดครั้งแรก ทำงานเมื่อกลับจาก bfcache event.persisted
onload ✅ ใช่ ❌ ไม่ ไม่มี
onpageshow ✅ ใช่ ✅ ใช่ true = จาก cache, false = โหลดใหม่

ตัวอย่างการใช้งาน

<!DOCTYPE html>
<html>
<body onpageshow="handlePageShow(event)">
  <h2>Tutorialspoint</h2>
  <p>Simply Easy Learning</p>
  <div id="status">สถานะ: กำลังโหลด...</div>
  
  <script>
    function handlePageShow(event) {
      const status = document.getElementById('status');
      if (event.persisted) {
        status.textContent = 'สถานะ: โหลดจาก Back/Forward Cache (bfcache)';
        status.style.color = 'orange';
        // อาจต้อง refresh ข้อมูลหรือ UI ที่เก่า
        refreshData();
      } else {
        status.textContent = 'สถานะ: โหลดหน้าใหม่ปกติ';
        status.style.color = 'green';
      }
    }
    
    function refreshData() {
      console.log('Refreshing data after bfcache restore...');
      // เรียก API อัปเดตข้อมูล ตรวจสอบสถานะ login เป็นต้น
    }
  </script>
</body>
</html>

กรณีที่ควรใช้ onpageshow

  • อัปเดตข้อมูลที่อาจล้าสมัยหลังจาก bfcache (ราคาหุ้น, สถานะการล็อกอิน, สินค้าคงเหลือ)
  • รีเซ็ตสถานะ UI (loading spinners, disabled buttons)
  • เริ่มต้น animation ใหม่
  • ตรวจสอบสิทธิ์การเข้าถึงอีกครั้ง

เหตุการณ์ที่เกี่ยวข้อง

  • onpagehide - ทำงานเมื่อออกจากหน้า (เก็บสถานะก่อน unload)
  • onbeforeunload - ก่อนปล่อยหน้า (ยืนยันการออก)
  • onunload - เมื่อปล่อยหน้า (ไม่ทำงานใน bfcache)
เคล็ดลับ: ใช้ event.persisted เพื่อแยกกรณีโหลดใหม่ vs กลับจาก cache เพื่อจัดการข้อมูลให้เหมาะสม