Recently I had an interview for a Front End Developer role with a medium sized company. One question came up that I found myself particularly void of answer for, and that was describing the purpose and benefits of the Page Visibility API. Well, unlucky for me, I was not prepared to answer this questions; and that is why I am writing this blog. So that you don’t get stuck in the same place I did!

Purpose

The main purpose of the Page Visibility API is to provide events you can watch for on your web page. They can let you know if the current page is visible, which is not always the case because of tabbed browsing. A user could just as easily be browsing their favorite social media site and leave your web page open in the background if not entirely by accident.

Usage

As you can probably imagine, there are many performance management uses for keeping track of a visibilitychange event. When a user navigates away from your page, you may want to pause a video or audio, stop an image carousel from advancing, or stop updating some any type of data. One of the main uses I would consider would be to keep track of how many views your page gets but tracking this event on some database or backend service.

To Dive Deeper

The document.visibilityState property can return only four possible values: visible, prerender, hidden, or unloaded. These allow you to preform actions like load a form for sign up when before loading the actual content of your page, as in the prerender value. Or prompt a user for feedback before they close their browser with unloaded.

Keeps a count of how many times we leave the page

Try It Out

Be creative when trying out this feature for the first time. Change colors, stop and start clocks, and try to work this into a video or audio usage. I am going to link the mozilla page for Page Visibility API. Happy Coding!

I ‘m a Web Developer and a Flatiron coding bootcamp alumni. I currently work in the financial tech industry as a Front End Engineer