With HTML5 came a plethora of useful API’s and added methods, one of those which didn’t really get as much visibility (ha, get it?) was the Page Visibility API.
What is the Page Visibility API?
The clue is in the name. It allows you to determine if a page is visible (a tab is focused or window being shown). Historically we haven’t really been able to reliably determine if a visitor is looking at a page and as such, can cause issues when media is being played.
The API is smart enough to work with both tabs and windows. It can accurately tell you if a user is focused and looking at your page. Especially handy if you have two side-by-side windows but focused on another and want to know if you’re site is legitimately and actually being viewed.
When should I use it?
The easiest use-case is when playing audio or video. If a user switches to another tab, you can pause any audio or video that might be currently playing. This not only makes for a better experience for users, it also prevents battery being wasted on devices and saves CPU as well.
There are other non-obvious uses as well. If you have any kind of looping animation (another CPU expense) you can pause or stop the animation when the user isn’t looking (after all, is there a point to a running animation if nobody can see it?).
How to use the Page Visiblity API?
Compared to other features in the HTML5 spec, the Page Visibility API is easy to use. After adding an event listener, it has two methods you can use. You most likely will only be using the method document.hidden
which returns true or false if the page is in-view or not. The other method document.visibilityState
tells you exactly why it is or is not in view with values; visible, hidden, prerender and unloaded. You can read up on each method value here.
HTML:
Javascript:
Page Visibility API Support
Surprisingly, the Page Visibility API is well supported and mostly free of vendor prefixes (except for Android). It is supported in IE10 and up, and on every modern browser (except Opera Mini, but who cares about Opera Mini anyway?).