Skip to content

Use visibilitychange event instead of unload event to improve performance and avoid a bug#715

Open
Flimm wants to merge 2 commits into
proginosko:masterfrom
Flimm:visibilitychange
Open

Use visibilitychange event instead of unload event to improve performance and avoid a bug#715
Flimm wants to merge 2 commits into
proginosko:masterfrom
Flimm:visibilitychange

Conversation

@Flimm
Copy link
Copy Markdown

@Flimm Flimm commented Apr 17, 2026

The "unload" event has these drawbacks:

  • It breaks the browser's back/forward cache (bfcache), worsening the performance of the browser when pressing the back button or forward button
  • It may be disabled entirely be the website's Permissions-Policy

It is preferable to use the "visibilitychange" or "pagehide" events instead. These events have been supported across browsers since April 2021 and July 2015, respectively. document.hidden has been supported across browsers since July 2015. This pull request makes the required change.

See:

https://web.dev/articles/bfcache#optimize

https://developer.mozilla.org/en-US/docs/Glossary/bfcache

The "unload" event has these drawbacks:

- It breaks the browser's back/forward cache (bfcache), worsening
  the performance of the browser when pressing the back button or
  forward button
- It may be disabled entirely be the website's Permissions-Policy

It is preferable to use the "visibilitychange" or "pagehide" events
instead. These events have been supported across browsers since April
2021 and July 2015, respectively. `document.hidden` has been supported
across browsers since July 2015.

See:

https://web.dev/articles/bfcache#optimize

https://developer.mozilla.org/en-US/docs/Glossary/bfcache
@proginosko
Copy link
Copy Markdown
Owner

I agree about avoiding the unload event. But wouldn't this PR mean that the timer would be removed from a page even when the user simply switches tabs?

The "unload" event has these drawbacks:

- It breaks the browser's back/forward cache (bfcache), worsening
the performance of the browser when pressing the back button or
forward button
- It may be disabled entirely be the website's Permissions-Policy

It is preferable to use the "pagehide" events instead. This event has
been supported across browsers since July 2015.

See:

https://web.dev/articles/bfcache#optimize

https://developer.mozilla.org/en-US/docs/Glossary/bfcache
@Flimm
Copy link
Copy Markdown
Author

Flimm commented May 11, 2026

I misread MDN documentation, d'oh! I feel a bit stupid now. It's better to use the pagehide event in this case. It is compatible with the bf-cache. I've pushed a new commit. (The old commit is no longer useful but I left it in the pull request to avoid overwriting history)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants