The HTML onunload event
The onunload attribute (the unload event) is deprecated and discouraged. It ran JavaScript as the page was being unloaded. It is unreliable — especially on mobile — and breaks the back/forward cache (bfcache). Use the pagehide event or the visibilitychange event instead.
Overview
The onunload event attribute runs JavaScript while the page is unloading (deprecated/discouraged). In JavaScript the event itself is named unload — drop the on prefix when you call addEventListener.
It is a window- or document-level event rather than one tied to a particular element, so it is handled on window or document. These events cover the page lifecycle, navigation, network status, messaging and similar global concerns.
You can wire this up with the inline onunload HTML attribute, but the modern, recommended approach is element.addEventListener('unload', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.
Discouraged. The unload event is unreliable (especially on mobile) and prevents the browser's back/forward cache. Use onpagehide or the visibilitychange event instead.
Syntax
<!-- Discouraged. Prefer pagehide / visibilitychange. -->
<body onunload="cleanup()">
Best practices
- Prefer
element.addEventListener('unload', handler)over the inlineonunloadattribute — it separates behavior from markup and allows multiple handlers. - Attach these on
window(ordocument) withaddEventListenerrather than as <body> attributes. - Keep these handlers fast — they run at moments that affect the whole page.
- Remove listeners you no longer need to avoid leaks in long-lived pages.
Frequently asked questions
What is the onunload event?
unload.Where do I attach this event?
window or document — these are global events, not tied to a single element.Can I use it as a body attribute?
window.addEventListener is preferred — it keeps behavior out of the markup and allows multiple handlers.Should I use the onunload attribute or addEventListener?
addEventListener('unload', …) in JavaScript. The inline onunload attribute works but mixes behavior into the markup and allows only one handler per element.