References

Beginner-friendly references for web development, with live, editable examples.

The HTML onunload event

Event Updated
Quick answer

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-level event rather than one tied to a particular element, so it is handled on window. 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 or with addEventListener, but neither is recommended: unload is unreliable and prevents the page entering the back/forward cache. Listen for pagehide or visibilitychange instead.

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 window.addEventListener('unload', handler) over the inline onunload attribute; it separates behavior from markup and allows multiple handlers.
  • Attach these on window with addEventListener rather 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?
It runs JavaScript while the page is unloading (deprecated/discouraged). In JavaScript the event is named unload.
Where do I attach this event?
On window: these are global events, not tied to a single element.
Can I use it as a body attribute?
You can (<body onunload> maps to window), but you should not use unload at all: however attached, it is unreliable and disables the back/forward cache. Use pagehide or visibilitychange instead.
Should I use the onunload attribute or addEventListener?
Neither. unload is discouraged and stops the page entering the back/forward cache however you attach it. Listen for pagehide or visibilitychange instead.