View video tutorial

HTML onpageshow Attribute

HTML

The HTML onpageshow attribute is an event handler that triggers a script to execute when the user navigates to a webpage.

Definition and Usage


➔ This is similar to the onload event but is more suitable for handling loaded pages and browser caches.

➔ The onload event does not fire when a page is loaded from the cache, but the onpageshow always fires.

➔ It is mainly used in the <body> element or Window object.

➔ This onpageshow event is often preferred over the older onload event because, unlike onload, onpageshow does not prevent the browser from caching the page. This provides a fast "back" navigation experience for the user.

➔ persisted is a boolean property that indicates whether the page is being cached (true) or completely unloaded (false).

Syntax
//In HTML
<body onpageshow="myFunction()">

//In Javascript
window.onpageshow = function(event) {
  // script goes here
};
// In Javascript EventListener
window.addEventListener("pageshow", function(event) {
  if (event.persisted) {
    // Page was loaded from cache
    console.log("Page from cached");
  } else {
    // Page was a fresh load
    console.log("Page with fresh load");
  }
});

Example
<!DOCTYPE html>
<html>
<head>
    <title>HTML onpageshow attribute example</title>
</head>
<body onpageshow="myFunction(event)">
    <h1>HTML onpageshow attribute example</h1>
    <h5 onclick="f2()"></h5>
    <p><a href="https://www.google.com">Go to other page and back again.</a></p>
    <script>
        //window.addEventListener("pageshow", myFunction );
        function myFunction(ev) {
            if (ev.persisted) {
                // Page was loaded from cache
                document.querySelector("h5").innerHTML = "Load from cache.";
            } else {
                // Page was a fresh load
                document.querySelector("h5").innerHTML = "Fresh new Load.";
            }
        }
        function f2() {
            document.querySelector("h5").innerHTML = "";
        }
    </script>
</body>
</html>

Applies to

This attribute can be used on the following element.

Attribute Element
onpageshow <body>