JavaScript unload Event

Summary: in this tutorial, you will learn how to use the JavaScript unload event that fires when the document is fully unloaded.

Note that you should never use the unload event, it’s only for reference.

Introduction to the JavaScript unload event

The unload event fires when a document has completely unloaded. Typically, the unload event fires when you navigate from one page to another.

The unload event is fired after:

At this moment, the HTML document is in the following state:

  • UI is not visible to the users and is not effective.
  • All the resources like img, iframe, etc., still exist.
  • An error won’t stop the unloading flow.

In practice, you should never use the unload event because it is not reliable on mobile devices and causes an issue with bfcache.

Handling the JavaScript unload event

To handle the unload event, you can use the addEventListener() method:

addEventListener('unload', (event) => {
    console.log('The page is unloaded');
});Code language: JavaScript (javascript)

Or assign an event handler to the onunload property of the window object:

window.onunload = (event) => {
    console.log('The page is unloaded');
};Code language: JavaScript (javascript)

Or assign an event handler to the onunload attribute of the <body> element:

<!DOCTYPE html>
<html>
<head>
    <title>JS unload Event Demo</title>
</head>
<body onunload="console.log('The page is unloaded')">

</body>
</html>Code language: HTML, XML (xml)

It’s a good practice to use the addEventListener() to register the unload event handler.

Summary

  • JavaScript fires the unload event when a document has been completely unloaded.
  • In practice, do not use the unload event.
Was this tutorial helpful ?