Tabbed browsing is great as it helps a user switch between different tabs which contain the information they care about. However, the user can only look at one tab at a time so optimizing your web experience to make sure it does not interfere with the goals of the user is important. As the Next Billion Users hit the web for the first time, many of them live in regions with unreliable infrastructure and use low-end devices. They may also be on flakky/limited bandwidth and keeping this in mind is good for both the user and the business. The user ends up gets a smooth experience and the business is able to get more users by providing better service.
As mentioned earlier, a user can only see one thing at a time so your web app’s background experience is as important as the foreground experience. Detecting the state of your web app (foreground or background) is something that can be easily achieved with the Page Visibility API.
As quoted from W3C spec, the page visibility API “defines a means to programmatically determine the visibility state of a top-level browsing context, and to be notified if the visibility state changes.” This means, work can be scaled down while the web app is in a background tab (hidden) and scaled up when it is in foreground (visible). This not only optimizes the performance of the web app, but can also be used to make runtime decisions that improve the overall user experience. Using the API is quite straight forward:
// listen for the visibilitychange event document.addEventListener('visibilitychange', handleVisibilityChange, false); // Handle page visibility change events function handleVisibilityChange() { if (document.visibilityState === "hidden") { // scale down work } else { // scale up work } }
The API can be used in a couple of scenarios:
Browser support is quite good and goes as far back as IE 10. A support table can be found below:
Browser support table for Page Visibility API
In the past, developers have used the blur and focus events to achieve the same results. Though imperfect solutions, they can be used in older browsers where the page visibility API is not supported. An example of usage would be like so:
if (document.visibilityState) { // use page visibility API } else { window.addEventListener(‘blur’, handleWindowBlur); window.addEventListener(focus, handleWindowFocus); }