In modern web development, users may frequently switch tabs or leave web pages running in the background. To avoid unnecessary resource wastage and enhance user experience, it is important to utilize thePage Visibility API Allows you to pause or reduce resource consumption when the page is not visible and resume normal operation when the page is visible again.
In this blog, I will show how the following scenario can be realized with the Page Visibility API:
- Pause video or audio playback when the user switches tabs.
- Stop resource-intensive animations when the page is not visible.
- Stop API requests when the page is not visible and restart them when the page is visible.
- Resumes the timed operation when the user returns to the page.
What is the Page Visibility API?
The Page Visibility API is a browser-provided API that tells us the visibility status of a page. When the page becomes invisible, we can pause some unnecessary actions, such as animation or media playback. This API provides two core functions:
-
: Returns a boolean indicating whether the page is currently hidden.
-
: Returns the visibility status of the page, which can be
'visible'
(page visible),'hidden'
(page hidden) or'prerender'
(The page is being pre-rendered). -
visibilitychange
event: when the visibility status of the page () is triggered on change.
visibilityState
role of
offer more than
More intuitive information. Not only does it tell you if the page is hidden, but it further distinguishes whether the page is being pre-rendered or not. For example, you can take different optimization measures depending on the status.
Browser compatibility
While the Page Visibility API is useful, its compatibility varies slightly from browser to browser. Here's how it's supported by the major browsers:
cap (a poem)
browser (software) | Support | releases |
---|---|---|
Chrome | be in favor of | Since version 33 |
Firefox | be in favor of | Since version 18 |
Safari | be in favor of | Since version 7 |
Edge | be in favor of | From version 12 |
Opera | be in favor of | Since version 20 |
visibilitychange
event
browser (software) | Support | releases |
---|---|---|
Chrome | be in favor of | From version 62 onwards |
Firefox | be in favor of | Since version 56 |
Safari | be in favor of | Since version 14.1 |
Edge | be in favor of | Since version 18 |
Opera | be in favor of | From version 49 |
Pause video playback when users switch tabs
Continuing to play a video when a user switches tabs wastes bandwidth and resources. With the Page Visibility API, it is possible to pause the video when the page is not visible and then automatically resume playback when the user returns.
const videoElement = ("video");
("visibilitychange", function() {
if ( === 'hidden') {
// Pause the video when the page is hidden
(); ("Pause video when page is hidden.
("Pause video when page is hidden"); } else if ( ( === 'visible') { // Pause video when page is hidden (); // Pause video when page is hidden.
} else if ( === 'visible') {
// Resume video playback when the page is visible
();
("Page is visible, video continues to play"); }
}
}).
Stop resource-intensive animations when the page is not visible
Animation can be a performance bottleneck, especially since it makes no sense to run animations when the page is not visible. With the Page Visibility API, we can pause animations when the page is not visible, reducing CPU and GPU consumption.
let animationRunning = true;
function startAnimation() {
if (!animationRunning) return;
// Assuming there is animation logic here
("Animation is running...") ;
requestAnimationFrame(startAnimation);
}
("visibilitychange", function() {
if ( === 'hidden' ) {
// Stop the animation when the page is hidden
animationRunning = false; ("Page is hidden, animation is running"); ("Page is hidden.
("Page hidden, animation running"); } else if ( === 'visible') { // Stop the animation when the page is hidden.
} else if ( === 'visible' ) {
// Resume animation when the page is visible
animationRunning = true; } else if ( === 'visible') { // Resume animation when the page is visible.
startAnimation(); } else if ( === 'visible') { // Resume animation when page is visible.
("Page visible, animation resumed"); }
}
}).
startAnimation();
Stop API requests when the page is not visible
In some cases, continuous data fetching may waste bandwidth. By detecting the visibility of a page, data requests can be stopped when the page is not visible, optimizing bandwidth usage.
let requestInterval;
function startFetchingData() {
requestInterval = setInterval(() => {
// analog (device, as opposed digital) API requesting
("Acquiring data...");
}, 5000);
}
function stopFetchingData() {
clearInterval(requestInterval);
("Stop getting data");
}
("visibilitychange", function() {
if ( === 'hidden') {
// Stop data fetching when page is hidden
stopFetchingData();
} else if ( === 'visible') {
// Restore data acquisition when page is visible
startFetchingData();
}
});
startFetchingData();
Resume timed operations when the page is visible
When the page is not visible, certain timed tasks can be suspended until the user returns to the page and then resume execution. This helps to increase the efficiency of resource utilization.
let intervalId.
function startTimer() {
intervalId = setInterval(() => {
("Timer is running...") ;
}, 1000);
}
function stopTimer() {
clearInterval(intervalId); }
("Timer stopped"); }
}
("visibilitychange", function() {
if ( === 'hidden') {
// Stop the timer when the page is hidden
stopTimer();
} else if ( === 'visible') {
// Resume the timer when the page is visible
startTimer(); } else if ( === 'visible') { // Resume the timer when the page is visible.
}
}).
startTimer();
Resume audio playback when the user returns to the page
Similar to video, continuing to play audio when the page is not visible is not only meaningless to the user, but also a waste of system resources. The Page Visibility API allows you to resume audio playback when the user returns to the page.
const audioElement = ("audio");
("visibilitychange", function() {
if ( === 'hidden') {
// Pause the audio when the page is hidden
(); ("Pause audio when page is hidden.
("Pause audio when page is hidden"); } else if ( ( === 'visible') { // Pause audio when page is hidden (); // Pause audio when page is hidden.
} else if ( === 'visible') {
// Resume audio playback when the page is visible
(); ("Page visible, audio paused"); } else if ( === 'visible') { // Resume audio playback when page visible.
("Page is visible, audio continues to play"); }
}
}).
reach a verdict
The Page Visibility API is a simple but very effective tool that enables developers to dynamically optimize the use of resources based on the visibility of a page. Combined with the, you can further refine the control of the page state, such as pausing certain actions while the page is pre-rendering.
This optimization not only improves user experience, but also significantly reduces the waste of system resources. By utilizing this API appropriately, we can pause background operations such as video, audio, animation, data requests, etc. and quickly resume them when the user refocuses on the page, achieving a double improvement in performance and experience.
During the development process, don't forget to consider browser compatibility to ensure a consistent user experience across all platforms. I hope this article can help you better grasp the Page Visibility API and apply it to real projects.
reference
- Page Visibility API - Web API | MDN ()
- Document: visibilitychange event - Web API | MDN ()
- Document: hidden attribute - Web API | MDN ()
- - Web API | MDN ()