原文链接:http://www.javaarch.net/jiagoushi/661.htm
如果页面不是显示在用户当前可视窗口,比如chrome,不在当前显示的tab页,那么我们可能不需要2s调用,因为那样只会浪费网络请求,查询了数据也没用,用户没有看到。那么我们就可以使用Page Visibility API来判断当前页是否是可视的tab上,如果是我们再去查,不是我们就不查了。Chrome,firefox最新版都支持了,IE也是支持的。
<!DOCTYPE html>
<html>
<body>
<div id="newswell"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
var newsDiv;
var active = true;
function isVisible() {
if("webkitHidden" in document) return !document.webkitHidden;
if("mozHidden" in document) return !document.mozHidden;
if("hidden" in document) return !document.hidden;
//worse case, just return true
return true;
}
function getData() {
$.ajax({url:"news.json"}).done(function(data) {
newsDiv.innerHTML += "<p><b>Posted at " + new Date() + "<br/>" + data.message;
//call it again in 2 seconds
if(isVisible()) window.setTimeout(getData, 2000);
else active = false;
}).fail(function(xhr,status,e) {
console.dir(e);
});
}
$(document).ready(function() {
newsDiv = document.querySelector("#newswell");
$(document).bind("visibilitychange webkitvisibilitychange mozvisibilitychange",function(e) {
console.log("VS CHANGE");
console.log(isVisible());
if(isVisible() && !active) {
active = true;
getData();
}
});
getData();
});
</script>
</body>
</html>
demo可以查看http://raymondcamden.com/demos/2013/may/28/crap.html,规范请查看http://www.w3.org/TR/page-visibility/