Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
HTML DOM PageTransition Event
The DOM PageTransitionEvent is fired when a user navigates to or away from a webpage. This event provides information about whether the page was loaded from the browser's cache (back-forward cache) or fetched fresh from the server.
The PageTransitionEvent is particularly useful for detecting when pages are restored from the browser's cache, which can affect the state of JavaScript variables and DOM elements.
Syntax
Following is the syntax for adding PageTransitionEvent listeners −
window.addEventListener('pageshow', function(event) {
// Handle pageshow event
});
window.addEventListener('pagehide', function(event) {
// Handle pagehide event
});
Properties of PageTransitionEvent
The PageTransitionEvent object has the following property −
| Property | Description |
|---|---|
| persisted | Returns true if the webpage was cached by the browser (loaded from back-forward cache), or false if it was loaded fresh from the server. |
PageTransitionEvent Types
There are two types of events that belong to the PageTransitionEvent object −
| Event | Description |
|---|---|
| pageshow | Fired when a webpage becomes visible to the user, either when initially loading or when restored from cache. |
| pagehide | Fired when a user navigates away from a webpage, either to another page or when closing the tab/window. |
Example − Basic PageTransitionEvent
Following example demonstrates the basic usage of PageTransitionEvent with both pageshow and pagehide events −
<!DOCTYPE html>
<html>
<head>
<title>PageTransitionEvent Example</title>
</head>
<body style="font-family: Arial, sans-serif; text-align: center; padding: 20px;">
<h1>PageTransitionEvent Demo</h1>
<p id="status">Page loaded</p>
<a href="https://www.tutorialspoint.com" target="_blank">Visit TutorialsPoint (New Tab)</a>
<br><br>
<button onclick="location.reload()">Reload Page</button>
<script>
window.addEventListener('pageshow', function(event) {
const statusEl = document.getElementById('status');
if (event.persisted) {
statusEl.textContent = 'Page restored from cache';
statusEl.style.color = 'green';
} else {
statusEl.textContent = 'Page loaded fresh from server';
statusEl.style.color = 'blue';
}
});
window.addEventListener('pagehide', function(event) {
console.log('Page is being hidden. Persisted:', event.persisted);
});
</script>
</body>
</html>
The status text changes based on whether the page was loaded from cache or fresh from the server −
PageTransitionEvent Demo Page loaded fresh from server (blue text) Visit TutorialsPoint (New Tab) [Reload Page]
Example − Detecting Cache State
Following example shows how to detect and respond to different cache states using the persisted property −
<!DOCTYPE html>
<html>
<head>
<title>Cache State Detection</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Cache State Detector</h2>
<div id="info" style="background: #f0f0f0; padding: 15px; margin: 10px 0; border-radius: 5px;">
Loading...
</div>
<p>Navigate to another page and use the back button to see cache behavior.</p>
<a href="data:text/html,<h1>Test Page</h1><a href='javascript:history.back()'>Go Back</a>">Go to Test Page</a>
<script>
window.addEventListener('pageshow', function(event) {
const infoDiv = document.getElementById('info');
const timestamp = new Date().toLocaleTimeString();
if (event.persisted) {
infoDiv.innerHTML = `
<strong>Page Restored from Cache</strong><br>
Time: ${timestamp}<br>
The page state has been preserved.
`;
infoDiv.style.backgroundColor = '#d4edda';
infoDiv.style.borderLeft = '4px solid #28a745';
} else {
infoDiv.innerHTML = `
<strong>Page Loaded Fresh</strong><br>
Time: ${timestamp}<br>
The page was loaded from the server.
`;
infoDiv.style.backgroundColor = '#cce7ff';
infoDiv.style.borderLeft = '4px solid #007bff';
}
});
window.addEventListener('pagehide', function(event) {
if (event.persisted) {
console.log('Page will be cached');
} else {
console.log('Page will be discarded');
}
});
</script>
</body>
</html>
The page displays different messages and styling based on whether it was restored from cache or loaded fresh.
Example − Refreshing Data on Cache Restore
Following example demonstrates how to refresh dynamic content when a page is restored from cache −
<!DOCTYPE html>
<html>
<head>
<title>Data Refresh on Cache Restore</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Dynamic Data Example</h2>
<p>Current time: <span id="current-time"></span></p>
<p>Page load count: <span id="load-count">0</span></p>
<div id="cache-info" style="margin: 20px 0; padding: 10px; background: #f8f9fa; border-radius: 5px;"></div>
<script>
let loadCount = 0;
function updateTime() {
document.getElementById('current-time').textContent = new Date().toLocaleString();
}
function updateLoadCount() {
loadCount++;
document.getElementById('load-count').textContent = loadCount;
}
window.addEventListener('pageshow', function(event) {
const cacheInfo = document.getElementById('cache-info');
updateTime();
updateLoadCount();
if (event.persisted) {
cacheInfo.innerHTML = '<strong>?? Page restored from cache</strong><br>Data refreshed automatically.';
cacheInfo.style.backgroundColor = '#fff3cd';
// Refresh any dynamic data when restored from cache
console.log('Refreshing data after cache restore...');
} else {
cacheInfo.innerHTML = '<strong>? Fresh page load</strong><br>All data is current.';
cacheInfo.style.backgroundColor = '#d1ecf1';
}
});
// Initial load
updateTime();
updateLoadCount();
</script>
</body>
</html>
This example shows how to automatically refresh time-sensitive data when a page is restored from the browser cache.
Common Use Cases
PageTransitionEvent is commonly used for −
Refreshing dynamic data − Update timestamps, user notifications, or real-time content when page is restored from cache.
Analytics tracking − Track page views correctly, distinguishing between fresh loads and cache restores.
State management − Reset or update JavaScript variables that may have become stale during caching.
Resource cleanup − Clean up resources like timers, intervals, or connections when leaving a page.
Browser Compatibility
PageTransitionEvent is supported in all modern browsers including Chrome, Firefox, Safari, and Edge. The persisted property is consistently supported across these browsers.
Conclusion
The PageTransitionEvent provides essential information about page navigation and caching behavior. The persisted property helps developers determine if a page was restored from cache, enabling proper handling of dynamic content and state management. This event is crucial for maintaining accurate page state in single-page applications and ensuring fresh data when needed.
