We can use the Page Visibility API to detect if a document is visible or not. Through this, we can stop unnecessary actions from being performed on the page.
Let’s say we have a page with a video or some background fetch to update the data or perform some animation. When we switch to another tab, we can improve performance or save memory by:
The Page Visibility API provides the following two properties under the document object:
hidden
:
a boolean value for a document’s hidden state. If true
, the document is hidden
, as seen below:document.hidden
visibilityState
: displays the current visibility state of the document. There are 4 states:visible
→ the page is visiblehidden
→ the page is not visibleprerender
→ the page is loaded in the background, but is not visited by the userunloaded
→ the page is in the process of being unloaded from memory.
prerender
andunloaded
are not supported in all browsers.
document.visibilityState
We also have the visibilitychange
event to detect any change in the visibility of the page, as shown below:
document.addEventListener('visibilitychange', function(ev) {
let state = document.visibilityState;
if(state === "visible")
console.log("Page is visible");
else if(state === "hidden")
console.log("Page is not visible");
});
In the code above, we can use the document.hidden
property instead of the document.visibilityState
.