Using the Page visibility API to optimize an application for background

Web developers should be aware that users often have a lot of tabs open in the background and it can have a serious effect on power usage and battery life. Work in the background should be kept to a minimum unless it’s absolutely necessary to provide a particular user experience. The Page visibility API should be used to detect when page is the backgrounded and suspend all unnecessary work like visual updates.

Code language: JavaScript

var doVisualUpdates = true;
 
document.addEventListener('visibilitychange', function(){
  doVisualUpdates = !document.hidden;
});
 
function update() {
  if (!doVisualUpdates) {
    return;
  }
  doStuff();
}