## The `onpageshow` Event
The `onpageshow` event fires when a user navigates to a webpage.
While similar to the `onload` event, the key difference is that `onload` does not fire when a page is loaded from the browser's cache (such as when a user clicks the "Back" or "Forward" button). The `onpageshow` event, however, fires **every time** the page is loaded, regardless of whether it comes directly from the server or from the browser's cache.
To determine whether a page was loaded directly from the server or retrieved from the cache, you can inspect the `persisted` property of the `PageTransitionEvent` object. This property returns `true` if the page was loaded from the cache, and `false` otherwise.
---
## Browser Support
The numbers in the table specify the first browser version that fully supports this event.
| Event | Chrome | Internet Explorer | Firefox | Safari | Opera |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **`onpageshow`** | Yes | 11.0 | Yes | 5.0 | Yes |
---
## Syntax
You can register the `pageshow` event handler in three ways:
### 1. In HTML
```html
```
### 2. In JavaScript (Property Assignment)
```javascript
object.onpageshow = function() {
myScript;
};
```
### 3. In JavaScript (Using `addEventListener`)
```javascript
object.addEventListener("pageshow", myScript);
```
> **Note:** The `addEventListener()` method is not supported in Internet Explorer 8 and earlier versions.
---
## Technical Details
| Attribute | Description |
| :--- | :--- |
| **Bubbles** | No |
| **Cancelable** | No |
| **Event Type** | `PageTransitionEvent` |
| **Supported HTML Tags** | `` (The event is registered on the `window` object) |
---
## Code Examples
### Example 1: Basic Usage
This example triggers a JavaScript function when the webpage is loaded.
```html
Welcome to YouTip!
An alert box will appear when this page is loaded.
```
### Example 2: Checking if the Page was Loaded from Cache
You can use the `persisted` property of the event object to check if the page was retrieved from the browser's cache (Back-Forward Cache / bfcache).
```javascript
window.addEventListener("pageshow", function(event) {
if (event.persisted) {
console.log("This page was loaded from the browser cache.");
} else {
console.log("This page was loaded fresh from the server.");
}
});
```
---
## Key Considerations: `onload` vs `onpageshow`
* **`onload`**: Fires only when the document is loaded for the first time. If you navigate away and click the "Back" button, the page is often restored from the browser's memory cache, and the `onload` event will **not** fire again.
* **`onpageshow`**: Fires every time the page is displayed, including when the page is restored from the browser's cache. This makes it highly useful for re-initializing state, updating dynamic data, or resetting UI elements when a user navigates back to your page.