Skip to content

Instantly share code, notes, and snippets.

@matiasherranz
Last active September 22, 2017 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matiasherranz/56664d19f17e387930152c2f68e97250 to your computer and use it in GitHub Desktop.
Save matiasherranz/56664d19f17e387930152c2f68e97250 to your computer and use it in GitHub Desktop.
On this gist I implemented a full demo / proof-of-concept for the Page Visibility API + Vanilla JS DOM ready implementation.
<!--
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
-->
<html>
<head>
<title>Aloha!</title>
<script>
// START OF: VanillaJS implementation for DOM ready
window.readyHandlers = [];
window.ready = function ready(handler) {
window.readyHandlers.push(handler);
handleState();
};
window.handleState = function handleState () {
if (['interactive', 'complete'].indexOf(document.readyState) > -1) {
while(window.readyHandlers.length > 0) {
(window.readyHandlers.shift())();
}
}
};
document.onreadystatechange = window.handleState;
// END
ready(function () {
// your page initialization code here
// the DOM will be available here
// Set the name of the hidden property and the change event for visibility
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
hidden = "hidden";
visibilityChange = "visibilitychange";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
var observedElement = document.getElementById("observedElement");
// If the page is hidden, log `hidden!`;
// if the page is shown, log `displayed!`;
function handleVisibilityChange() {
if (document[hidden]) {
console.log('hidden!')
document.title = "I'm hidden";
} else {
console.log('displayed!')
document.title = "Look at me!";
}
}
// Warn if the browser doesn't support addEventListener or the Page Visibility API
if (typeof document.addEventListener === "undefined" || typeof document[hidden] === "undefined") {
console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
} else {
// Handle page visibility change
document.addEventListener(visibilityChange, handleVisibilityChange, false);
}
});
</script>
</head>
<body>
<div id="observedElement">I think I'm being observed!</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment