What is the usage of onpageshow event in JavaScript?

The onpageshow event triggers in JavaScript when a user navigates to a web page, including when the page loads for the first time or when returning from the browser's back/forward cache (bfcache).

Syntax

// HTML attribute
<body onpageshow="functionName()">

// Event listener
window.addEventListener('pageshow', function(event) {
    // Handle page show
});

Example: Basic Usage

Here's how to implement the onpageshow event using HTML attribute:

<!DOCTYPE html>
<html>
   <body onpageshow="newFunc()">
      <p>On first visit, a welcome message is visible.</p>
      <script>
         function newFunc() {
            alert("Welcome!");
         }
      </script>
   </body>
</html>

Example: Using Event Listener

A more flexible approach using addEventListener():

<!DOCTYPE html>
<html>
   <body>
      <p id="message">Page loaded!</p>
      <script>
         window.addEventListener('pageshow', function(event) {
            console.log('Page is now visible');
            
            // Check if page was restored from cache
            if (event.persisted) {
               console.log('Page restored from cache');
            } else {
               console.log('Page loaded fresh');
            }
         });
      </script>
   </body>
</html>

Key Features

The pageshow event object provides a persisted property:

  • event.persisted = true: Page restored from browser cache
  • event.persisted = false: Page loaded fresh

Common Use Cases

  • Refreshing dynamic content when returning to a cached page
  • Tracking page visits and navigation patterns
  • Reinitializing JavaScript components after cache restoration
  • Updating timestamps or user session information

Browser Compatibility

The onpageshow event is supported in all modern browsers including Chrome, Firefox, Safari, and Edge.

Conclusion

The onpageshow event is essential for handling both fresh page loads and cache restorations. Use the persisted property to differentiate between the two scenarios and update your page accordingly.

Updated on: 2026-03-15T23:18:59+05:30

242 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements