I have a web Application running on a controller (Scarcely limited processing, memory and network bandwidth). The page is basically a simple HTML file full of LEDs that should be updated on an interval. On each interval, Javascript sends an Ajax request to the server and updates all the LEDs based on the reply. Now this works fine!
The problem is when the user opens one of these pages and start browsing other stuff. For security and economical reasons, we don't want to update the page when the client is not seeing this page. This is the algorithm:
I developed this little test code to see how page events work (see live on jsFiddle):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function m(msg){
document.getElementById("logplace").innerHTML+=msg+"<br/>";
}
</script>
</head>
<body onblur="m('Blur')" onerror="m('Error')" onfocus="m('Focus')" onload="m('Load')" onresize="m('Resize')" onunload="m('Unload')">
<span id="logplace"></span>
</body>
</html>
I need to page to be only updated if the user is currently viewing it. I searched the Stackoverflow and the following threads don't seem to be the answer:
PS. JQuery exists on the server as well. But if there is a simpler way, I prefer not to use JQuery.
var focused = false;
function onBlur() {
focused = false;
};
function onFocus(){
focused = true;
};
if (/*@cc_on!@*/false) { // check for Internet Explorer
document.onfocusin = onFocus;
document.onfocusout = onBlur;
} else {
window.onfocus = onFocus;
window.onblur = onBlur;
}
Then your javascript can check
if (focused)
{
// process ajax
}
source: http://www.thefutureoftheweb.com/blog/detect-browser-window-focus
Check out the demo he created so you can see it in action: http://www.thefutureoftheweb.com/demo/2007-05-16-detect-browser-window-focus/
With that in mind, if your page uses an interval timer to update, when the window loses focus, you could kill the interval, then start it again when the window is focused.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With