以下是一个简单的例子,演示如何使用 onpageshow 事件:
<!DOCTYPE html>
<html>
<head>
<title>onpageshow Event Example</title>
</head>
<body onpageshow="handlePageShow(event)">
<h1>This is a sample page</h1>
<script>
// 处理页面显示事件
function handlePageShow(event) {
if (event.persisted) {
alert("Page is being shown from the cache.");
} else {
alert("Page is being shown for the first time.");
}
}
</script>
</body>
</html>
在这个例子中,<body> 元素上附加了 onpageshow 事件,并调用了 handlePageShow 函数。在函数中,通过检查 event.persisted 属性,我们可以判断页面是首次加载还是从浏览器缓存中恢复。如果 event.persisted 为 true,表示页面是从缓存中恢复的。
当用户首次访问页面时,会显示 "Page is being shown for the first time." 的警告框。如果用户导航回页面(且浏览器支持页面缓存),再次显示页面时会显示 "Page is being shown from the cache." 的警告框。这可以用于执行在页面加载或从缓存中恢复时所需的不同操作。
转载请注明出处:http://www.zyzy.cn/article/detail/6242/JavaScript 和 HTML DOM