Skip to content

Instantly share code, notes, and snippets.

@Raynos
Forked from Zirak/gist:1677020
Created January 25, 2012 21:42
Show Gist options
  • Select an option

  • Save Raynos/1678976 to your computer and use it in GitHub Desktop.

Select an option

Save Raynos/1678976 to your computer and use it in GitHub Desktop.
Visibility API
//http://www.w3.org/TR/2011/WD-page-visibility-20110602/
(function () {
"use strict";
//no need to shim if it's already there
if ( 'hidden' in document && 'onvisibilitychange' in document ) {
return;
}
//fail silently if the browser sux
if (
!Array.prototype.forEach ||
!Object.defineProperty ||
!document.addEventListener ||
!window.addEventListener
) {
return;
}
//check to see if there's a native implementation
var prefixes = [ 'webkit', 'moz', 'o', 'ms' ], native = '';
prefixes.some(function ( prefix ) {
if ( (prefix + 'Hidden') in document ) {
native = prefix;
return true;
}
});
//* Y U NO INLINE
var hiddenGetter, stateGetter;
if ( native ) {
hiddenGetter = function () {
return document[ native + 'Hidden' ];
};
} else {
hiddenGetter = function () {
return hidden;
};
}
//* Y U CREATE NEW visibilityStates OBJECT PER FUNCTION CALL
stateGetter = function () {
//corresponding values to document.hidden
var visibilityStates = {
'true' : 'hidden',
'false' : 'visible'
};
return visibilityStates[ document.hidden ];
};
//will be called whenever the visibility has been changed
var visibilityChange = function () {
document.hidden = hiddenGetter();
document.visibilityState = stateGetter();
//create the visibilitychange event
var evt = document.createEvent( 'Event' );
evt.initEvent( 'visibilitychange', true, true );
//you're FIRED!
document.dispatchEvent( evt );
//check for document.onvisibilitychange and call it if it exists
var vischange = 'onvisibilitychange'; //it's really long to write...
if ( document[vischange] && document[vischange].call ) {
document[ vischange ].call( document, evt );
}
},
hidden = false;
//add the event listeners to tap into native functionality
if ( native ) {
document.addEventListener( native + 'visibilitychange', visibilityChange );
} else {
//the window.focus and window.blur events are, well, close enough
window.addEventListener( 'focus', function () {
hidden = false;
visibilityChange();
});
window.addEventListener( 'blur', function () {
hidden = true;
visibilityChange();
});
}
//add document.hidden, document.visibilityState and document.onvisibilitychange
Object.defineProperties(document, {
hidden : {
//* Y U NO INLINE
value : hiddenGetter(),
writable : true,
configurable : true
},
visibilityState : {
//* Y U NO INLINE
value : stateGetter(),
writable : true,
configurable : true
},
onvisibilitychange : {
value : null,
writable : true,
configurable : true
}
});
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment