以下代码是使用 navigator.onLine 的替代方法 - 通过检查服务器是否可访问。
“简单”的问题——我该如何让它发挥作用?
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;
}
}
上面的代码取自文章: http: //louisremi.com/2011/04/22/navigator-online-alternative-serverreachable/但我不知道为什么它不起作用。