如果已连接,如何使用javascript刷新页面? [英] how to refresh page using javascript if connected?
问题描述
我有一个网页,希望使用以下代码每2分钟刷新一次:
I have a web page that i want it to refresh every 2 minutes, using the following code:
location.reload();
问题是我假设用户已连接;但是,如果碰巧他/他没有在线连接,则该页面将失败并提供默认浏览器(无连接错误页面);并且页面永远不会刷新,除非由用户手动
The problem is that I assume that the user is connected; but if it happened that s/he is not connected online the page will fail and give the default browser(no connection error page ); and the page will never refresh except manually by the user
我可以使用ping机制来确定天气是否要刷新吗?
can i include a ping mechanism to decide weather to refresh or not?
推荐答案
您可以使用navigator.onLine
检测网络连接
You can use navigator.onLine
to detect a network connection
setInterval(function() {
if (navigator.onLine) {
location.reload();
}
}, 120000); /* 120000 ~> 2 minutes */
否则,您可以改为对同域资源使用HEAD
ajax请求并仅在响应返回200/304
状态(例如
otherwise, you may use instead an HEAD
ajax request to a same-domain resource and refresh the page only if the response return a 200/304
status, e.g.
setInterval(function() {
$.ajax({
url : "/favicon.ico", /* or other resource */
type : "HEAD"
})
.done(function() {
location.reload();
});
}, 120000); /* 120000 ~> 2 minutes */
这篇关于如果已连接,如何使用javascript刷新页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!