Skip to content

Instantly share code, notes, and snippets.

@scottsappen
Created July 1, 2013 15:03
Show Gist options
  • Save scottsappen/5901627 to your computer and use it in GitHub Desktop.
Save scottsappen/5901627 to your computer and use it in GitHub Desktop.
HTML5 page visibility API example http://ssbits.wordpress.com/category/html5/
//Call this function which will do the work of rendering if needed
visChange();
//check if the div_blogroll is visible on the page, if so, render it
function visChange() {
var divBlog = document.getElementById('div_blogroll');
if (divBlog) {
if (!isHidden())
doLoadBlogRoll();
}
}
//pagevisibility API
function getHiddenProp() {
var prefixes = ['webkit', 'moz', 'ms', 'o'];
// if 'hidden' is natively supported just return it
if ('hidden' in document) return 'hidden';
// otherwise loop over all the known prefixes until we find one
for (var i = 0; i < prefixes.length; i++) {
if ((prefixes[i] + 'Hidden') in document)
return prefixes[i] + 'Hidden';
}
// otherwise it's not supported
return null;
}
//helper function
function isHidden() {
var prop = getHiddenProp();
if (!prop) return false;
return document[prop];
}
//use the property name to generate the prefixed event name
var visProp = getHiddenProp();
if (visProp) {
var evtname = visProp.replace(/[H|h]idden/, '') + 'visibilitychange';
document.addEventListener(evtname, visChange);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment