javascript Page Visibility API
原文链接:http://www.javaarch.net/jiagoushi/661.htm
javascript Page Visibility API
Page Visibility API是判断页面是否在当前窗口展示,如果显示在当前窗口,则可以选择做或者不做一些事情。
比如我们使用一个AJAX 调用从后台每隔2s查询一些数据
<!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; function getData() { $.ajax({url:"news.json"}).done(function(data) { newsDiv.innerHTML += "<p><b>Posted at " + new Date() + " " + data.message; //call it again in 2 seconds window.setTimeout(getData, 2000); }).fail(function(xhr,status,e) { console.dir(e); }); } $(document).ready(function() { newsDiv = document.querySelector("#newswell"); getData(); }); </script> </body> </html>
如果这个页面不是显示在用户当前可视窗口,比如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() + " " + 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/