Tuesday, August 9, 2011

HTML5: Page Visibility API

Today I stumbled upon an interesting API being introduced in HTML5 – Page Visibility API. As the name suggests, the API facilitates the developers to programmatically determine the current visibility of the page. User interface designers can take advantage of this API, which is still in Working Draft, to give better experience to the visitors. This will also help in better resource utilization. For example, if your page has an animation, you can efficiently render it only when the page is visible without having to hog the resources. The specification introduces a new interface named “DocumentVisibility” that provides Web applications with the means to programmatically determine the current visibility of a page and be notified of visibility changes. Check out the demo here.

The specification includes three main parts:

  1. Attribute document.hidden: This is a Boolean attribute of DocumentVisibility interface indicating if the page is hidden from view. It will return ‘false’ even if part of the page is visible. There are vendor specific implementations for this. It is implemented as document.msHidden in IE and document.webkitHidden in Chrome.
  2. Attribute document.visibilityState: This is an attribute of DocumentVisibility interface indicating the state of the page. The specification includes three different states: “hidden”, “visible”, “preview” – The page is not visible but a preview of it is visible. Again, its open to vendors to define their own states. Its implemented as document.msVisibilityState in IE and document.webkitVisibilityState in Chrome. The major deference, however, is that document.msVisibilityState is a numeric value where as document.webkitVisibilityState is a string value. Hence, its better to stick to document.hidden till the API matures.
  3. Event visibilitychange: The visibilitychange event will be fired whenever a change is made to the document.visibilityState attribute. We can listen to this event on document and as mentioned in point#2, its advisable to use document.hidden to find out the new state within the listener. Here, again, you will have to listen to vendor specific events.

Demo:

I have setup this demo page to explore the Page Visibility API. It runs a timer to show clock on the page. The timer will be disabled whenever we move away from the page and will be re-activated as we enter the page with the adjusted clock timing. Smart developers always view the source. View the page source to know more.

Browser Support:

  • Internet Explorer (10+)
  • Chrome (12+)

Page Visibility API will be really useful if vendors follow the specifications completely and move away from the vendor prefixes. More info about Page Visibility can be found here.

-- Varun

No comments:

Post a Comment

google-site-verification: googlea4d68ed16ed2eea6.html