Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Javascript Ajax calls only when the page is being viewed

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:

A flowchart of the page update 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:

  • Keep track of which tab was being viewed when page is refreshed
  • How to run multiple ajax calls on one page
  • Function repeating when page not being viewed

PS. JQuery exists on the server as well. But if there is a simpler way, I prefer not to use JQuery.

like image 674
AlexStack Avatar asked Oct 08 '22 18:10

AlexStack


1 Answers

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.

like image 120
Francis Lewis Avatar answered Oct 12 '22 02:10

Francis Lewis