【发布时间】:2015-12-05 23:42:57
【问题描述】:
我目前正在开发一个网络应用程序。我正在使用 Appcache。 所以我想要做的实际上很简单:如果用户在没有互联网连接的情况下加载页面,他会看到一个带有“离线”文本的按钮,否则会看到“在线”文本。 我的第一种方法是使用 offline.js,但它无法正确检测用户何时在线/离线。
所以我试过这段代码:
function serverReachable() {
// IE vs. standard XHR creation
var x = new (window.ActiveXObject || XMLHttpRequest)("Microsoft.XMLHTTP"),
s;
x.open(
// requesting the headers is faster, and just enough
"HEAD",
// append a random string to the current hostname,
// to make sure we're not hitting the cache
"//" + window.location.hostname + "/?rand=" + Math.random(),
// make a synchronous request
false
);
try {
x.send();
s = x.status;
// Make sure the server is reachable
return (s >= 200 && s < 300 || s === 304);
// catch network & other problems
} catch (e) {
return false;
}
}
但是,当通过 AppCache 加载页面时,XHR-Requests 似乎会失败。
使用navigator.onLine 是不可取的,因为我们的大多数用户都在使用 Chrome。
有解决办法吗? 谢谢
【问题讨论】:
-
offline.js 应该没问题。你到底遇到了什么问题?
-
我使用了
Offline.check()和Offline.state,但是每当我从Appcache 加载网站时Offline.state返回down- 与我之前的代码相同的问题。 -
这很奇怪,看看这个,这可能对你有帮助:gavick.com/blog/detect-offline-browser
-
@RaahimGhauri 我没有在头部加载脚本,而是在
body的末尾。也许这是导致问题的原因,将尝试。谢谢! -
这很奇怪......我会看看我能做什么,但不会承诺太多。
标签: javascript html xmlhttprequest