Event onpageshow ทริกเกอร์เมื่อ หน้าแสดงขึ้น รวมถึงโหลดครั้งแรก และเมื่อRestore จาก Back-Forward Cache (bfcache)
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<body onpageshow="newFunc()">
<p>On first visit, a welcome message is visible.</p>
<script>
function newFunc() {
alert("Welcome!");
}
</script>
</body>
</html>
คำอธิบาย
- ทริกเกอร์ตอน Load ครั้งแรก และ ตอน Restore จาก bfcache
- Event Object มี Property
persisted:true= Restore จาก bfcache,false= Load ปกติ
ใช้แยก Logic: Initialize ครั้งแรก vs Restore State
ตัวอย่างใช้ persisted
window.addEventListener('pageshow', (e) => {
if (e.persisted) {
console.log('Restored from bfcache - refresh data?');
// อาจต้อง Refresh Data/Token ที่หมดอายุ
refreshAuthToken();
} else {
console.log('Fresh load - initialize app');
initializeApp();
}
});
เปรียบเทียบ Load Events
| Event | ทริกเกอร์ | bfcache Restore |
|---|---|---|
DOMContentLoaded | DOM Ready | ไม่ |
load | Resources All Loaded | ไม่ |
pageshow | Page Visible | ใช่ (persisted=true) |
ใช้เมื่อไหร่: ต้องการรู้ว่าหน้าถูก Restore จาก Cache (เช่น Refresh Token, Re-validate State, Re-attach WebSocket)