How to listen to browser window visibility
Recently at work, I had to find a solution where we can pause scheduling some animation frame rendering while the window is not visible.
Page Visibility API to rescue
With the following simple piece of code, we can listen to window visibility.
js
document.addEventListener('visibilitychange', console.log);// {// isTrusted: true// bubbles: true// cancelBubble: false// cancelable: false// composed: false// currentTarget: null// defaultPrevented: false// eventPhase: 0// path: (2) [document, Window]// returnValue: true// srcElement: document// target: document// timeStamp: 22899// type: "visibilitychange"// }
A document is hidden when the user navigates to a different tab or minimizes the browser.
Practical use cases
- Pausing CPU/GPU intensive actions like pausing a video and resuming it when the user lands in.
- Pausing animations with infinite durations. It does not make sense to keep the animations running when there is no one to see it /O\.
- Defer api calls that display realtime data to the user such as dashboard.
- Mostly importantly
requestAnimationFrame
calls. We can callcancelAnimationFrame
to cancel those calls when the window is hidden and allow them to execute. This is exactly what I had to do to improve performance.
With some update to the above piece of code, lets branch out the course of actions.
js
document.addEventListener('visibilitychange', () => {if(document.hidden) {// Pause those CPU/GPU, power consuming tasks here.} else {// Resume those back again here.}});
Based on your framework of choice, either create an util or service to determine the visibility or listen to those visibility changes.