Ev Onload
## HTML onload Event Attribute
The `onload` event attribute fires immediately after a document, element, or resource has finished loading. It is most commonly used on the `` element to execute JavaScript code once the entire web page (including DOM, images, stylesheets, and scripts) has fully loaded.
---
### Interactive Example
Run a JavaScript function immediately after the document has fully loaded:
```html
`, `
```
#### 2. Dynamic Event Binding in JavaScript
Instead of inlining the `onload` attribute directly in your HTML markup, it is highly recommended to bind it dynamically using JavaScript for cleaner separation of concerns.
```javascript
// Option A: Using the window.onload property
window.onload = function() {
console.log("Page fully loaded via window.onload");
};
// Option B: Using addEventListener (Recommended)
window.addEventListener('load', (event) => {
console.log("Page fully loaded via addEventListener");
});
```
---
### Important Considerations
1. **`onload` vs. `DOMContentLoaded`**:
* `onload` waits for the **entire page** to load, including all images, stylesheets, and frames. This can cause a delay on media-heavy pages.
* `DOMContentLoaded` fires as soon as the **HTML document (DOM)** is fully parsed and loaded, without waiting for stylesheets, images, and subframes to finish loading. Use `DOMContentLoaded` if your script only needs to manipulate DOM elements.
2. **Single Listener Limitation**: If you use the inline `` or `window.onload = function`, you can only assign a single listener. Subsequent assignments will overwrite the previous ones. To attach multiple load event listeners, always use `window.addEventListener('load', handler)`.
YouTip