Running Javascript Ajax only calls when viewing a page

I have a web application running on a controller (limited processing, memory and network bandwidth). The page is basically a simple HTML file full of LEDs that needs to be updated at intervals. At each interval, Javascript sends an Ajax request to the server and updates all the LEDs based on the response. Now it works great!

The problem is when the user opens one of these pages and starts viewing other materials. For security and economy reasons, we do not want to refresh the page when the client does not see this page. This is the algorithm:

A flowchart of the page update algorithm

, , (. 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>

, , . Stackoverflow, :

PS. JQuery . , JQuery.

+5
3
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;
}

javascript

if (focused)
{
    // process ajax
}

: http://www.thefutureoftheweb.com/blog/detect-browser-window-focus

, , : http://www.thefutureoftheweb.com/demo/2007-05-16-detect-browser-window-focus/

, , , , , .

+4

, db. is_viewed +1 , -1 , . 0, . ( Ajax), , .

0

, ( ) . , DOM .

.

var pageControl=open('page.html','page name','width=200,height=200')

pageControl javascript.

It solves the problem by letting you refresh the page when the focus is on windows that control updates from another window or from the main window. The only potential hurdle from here would be compatibility.

Deciding the main window can be a little more complicated. But if you do this from another window, you can imagine that if you do not find the focus of the window, you will not run the update script .. otherwise, run it!

0
source

All Articles