Lighthouse: Avoid unload event listeners
unload event listeners can help you take advantage of the back/forward cache (aka bfcache) in modern browsers.
The bfcache is an in-memory browser cache that enables near-instant backward and forward navigation when using the browser's backward and forward buttons.
unload event listeners, the bfcache is disabled - which means instant back and forth navigation isn't possible, degrading your visitors' page experience.
How does your site score on this audit?
How does avoiding unload event listeners affect page performance?
In the simplest terms, this is akin to "pausing" your page when navigating away, and then "resuming" when you return to it.
We've all been in situations where we visit a page and then click on a link to go to another page, but we realize that's not the page we really want and click the back button to return to the first page.
If the browser encounters an
unload handler may cause issues with the page after it is restored with bfcache.
In other words, the browser will elect not to enable the bfcache if it discovers an
unload event handler in order to ensure your page retains functionality between back and forth states.
unload event on modern browsers breaks near-instant back and forth navigation.
It is these kinds of navigations (particularly on mobile devices) where bfcache is very beneficial to page performance as it can retrieve whole pages quicker than the browser's HTTP cache.
If you add an
unload event to your page, you're likely depriving your visitors of the opportunity to experience near-instant navigations when using the browser's backward and forward buttons.
In addition, having
unload event listeners on your page slows down performance in Firefox, and the code probably won't even execute most of the time in Chrome and Safari.
unload listeners shouldn't be used as modern browsers have better methods to determine when a user has navigated away from the page.
How does GTmetrix trigger this audit?
unload event listener.
How to fix this audit?
To fix this audit, remove any
unload event listeners on your page.
Instead, consider using
visibilitychange events to ensure that your page can still utilize bfcache, and reap all its associated benefits.
Refer to this external resource for more information on using