如何使用jQuery检查是否有一个互联网连接?这样我就可以设置一些条件,比如“在制作过程中使用谷歌缓存版本的JQuery,在开发过程中使用谷歌缓存版本或本地版本,这取决于互联网连接”。
当前回答
我有一个解决办法,在这里工作,检查是否有网络连接:
$.ajax({
url: "http://www.google.com",
context: document.body,
error: function(jqXHR, exception) {
alert('Offline')
},
success: function() {
alert('Online')
}
})
其他回答
好吧,也许在游戏中有点晚了,但是用在线图像检查怎么样? 我的意思是,OP需要知道他是否需要抓取谷歌CMD或本地JQ副本,但这并不意味着浏览器无论如何都不能读取Javascript,对吧?
<script>
function doConnectFunction() {
// Grab the GOOGLE CMD
}
function doNotConnectFunction() {
// Grab the LOCAL JQ
}
var i = new Image();
i.onload = doConnectFunction;
i.onerror = doNotConnectFunction;
// CHANGE IMAGE URL TO ANY IMAGE YOU KNOW IS LIVE
i.src = 'http://gfx2.hotmail.com/mail/uxp/w4/m4/pr014/h/s7.png?d=' + escape(Date());
// escape(Date()) is necessary to override possibility of image coming from cache
</script>
这只是我的小意思
一个更简单的解决方案:
<script language="javascript" src="http://maps.google.com/maps/api/js?v=3.2&sensor=false"></script>
之后在代码中:
var online;
// check whether this function works (online only)
try {
var x = google.maps.MapTypeId.TERRAIN;
online = true;
} catch (e) {
online = false;
}
console.log(online);
当没有联机时,谷歌脚本将不会被加载,从而导致抛出异常的错误。
针对您的具体情况,最好的选择可能是:
在close </body>标签之前:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
考虑到您的问题是围绕jQuery的,这可能是最简单的方法。
如果你想要一个更健壮的解决方案,你可以尝试:
var online = navigator.onLine;
阅读更多关于离线web应用的W3C规范,但是请注意,这将在现代web浏览器中运行得最好,在旧的web浏览器中这样做可能无法正常工作,或者根本无法正常工作。
另外,向您自己的服务器发送XHR请求也不是一种测试连接的糟糕方法。考虑到其他答案之一,XHR有太多的故障点,如果你的XHR在建立连接时有缺陷,那么它在日常使用中也会有缺陷。如果您的站点由于某种原因无法访问,那么在同一服务器上运行的其他服务也可能无法访问。这个决定由你决定。
我不建议向其他人的服务(甚至是google.com)发出XHR请求。向服务器发出请求,或者根本不请求。
“在线”是什么意思?
There seems to be some confusion around what being "online" means. Consider that the internet is a bunch of networks, however sometimes you're on a VPN, without access to the internet "at-large" or the world wide web. Often companies have their own networks which have limited connectivity to other external networks, therefore you could be considered "online". Being online only entails that you are connected to a network, not the availability nor reachability of the services you are trying to connect to.
要确定一个主机是否可以从您的网络访问,您可以这样做:
function hostReachable() {
// Handle IE and more capable browsers
var xhr = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" );
// Open new request as a HEAD to the root hostname with a random param to bust the cache
xhr.open( "HEAD", "//" + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false );
// Issue request and handle response
try {
xhr.send();
return ( xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304) );
} catch (error) {
return false;
}
}
你也可以在这里找到要点:https://gist.github.com/jpsilvashy/5725579
本地实现的详细信息
有些人评论说,“我总是得到错误的回复”。这是因为您可能正在本地服务器上进行测试。无论您向哪个服务器发出请求,您都需要能够响应HEAD请求,当然,如果您愿意,可以将其更改为GET。
发送XHR请求很糟糕,因为如果特定的服务器宕机,它可能会失败。相反,使用google的API库来加载他们的jQuery缓存版本。
你可以使用google API在加载jQuery后执行回调,这将检查jQuery是否加载成功。类似下面的代码应该可以工作:
<script type="text/javascript">
google.load("jquery");
// Call this function when the page has been loaded
function test_connection() {
if($){
//jQuery WAS loaded.
} else {
//jQuery failed to load. Grab the local copy.
}
}
google.setOnLoadCallback(test_connection);
</script>
谷歌API文档可以在这里找到。
5年后的版本:
今天,如果你不想深入了解本页所描述的不同方法的细节,就可以找到适合你的JS库。
其中一个是https://github.com/hubspot/offline。它检查预定义URI的连通性,默认情况下是您的favicon。当用户的连接重新建立时,它会自动检测,并提供up和down等整洁的事件,您可以将其绑定以更新UI。
推荐文章
- 在JavaScript中根据键值查找和删除数组中的对象
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- jQuery: keyPress退格键不火?
- XMLHttpRequest Origin null不允许Access-Control-Allow-Origin for file:/// to file:///(无服务器)
- 重置setTimeout
- jQuery有不聚焦的方法吗?
- jQuery -替换字符串中某个字符的所有实例
- Ng-repeat结束事件
- 模糊vs聚焦-有什么真正的区别吗?
- 如何用jQuery / JavaScript解析JSON数据?
- jQuery在请求体中发布有效的json
- jQuery中的live()转换为on()
- jQuery等价于JavaScript的addEventListener方法
- jQuery需要避免的陷阱
- 用jQuery切换DIV背景图像