私は同じ機能を必要としていましたが、多くの検索の結果、この機能が見つかりました:
http://louisremi.com/2011/04/22/navigator-online-alternative-serverreachable/
リンクがダウンした場合に備えて、記事のコードを次に示します。
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.href.split("?")[0] + "?" + 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;
}
}
上記のコードには、コメントの下部に投稿されている localhost を操作するための Scott Jehl による修正が含まれていることに注意してください。そして、これは同じ関数の jQuery バージョンへのリンクです。
https://gist.github.com/scottjehl/947084
そして、そのリンクからのコード:
function serverReachable() {
var s = $.ajax({
type: "HEAD",
url: window.location.href.split("?")[0] + "?" + Math.random(),
async: false
}).status;
return s >= 200 && s < 300 || s === 304;
};
私はこのテクニックが本当に効果的であることを発見しました。リクエストはヘッダー情報のみを対象としているため、かなり高速で、すべてのブラウザで機能します。大成功!:)
私と同じように、他の人もこれが役立つことを願っています。:)