javascript – 在浏览器中检测离线模式的最佳方法是什么?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 在浏览器中检测离线模式的最佳方法是什么?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1751字,纯文字阅读大概需要3分钟。
内容图文
![javascript – 在浏览器中检测离线模式的最佳方法是什么?](/upload/InfoBanner/zyjiaocheng/766/06c0b8d8a85e4288828e11ccf956eb28.jpg)
我有一个Web应用程序,其中有许多Ajax组件在页面内经常刷新(它是各种各样的仪表板).
现在,我想为页面添加功能,以便在没有Internet连接时,页面的当前内容不会更改,并且页面上会显示一条消息,指出页面处于脱机状态(当前,这些不同的小工具都在页面尝试刷新自己,发现没有连接,他们的旧数据消失了).
那么,最好的方法是什么?
解决方法:
处理此问题的一种方法可能是使用显式超时方法扩展XmlHTTPRequest对象,然后使用它来确定您是否在脱机模式下工作(即,对于不支持navigator.onLine的浏览器).以下是我在一个站点(使用Prototype库的站点)上实现Ajax超时的方法. 10秒(10,000毫秒)后,它将中止调用并调用onFailure方法.
/**
* Monitor AJAX requests for timeouts
* Based on the script here: http://codejanitor.com/wp/2006/03/23/ajax-timeouts-with-prototype/
*
* Usage: If an AJAX call takes more than the designated amount of time to return, we call the onFailure
* method (if it exists), passing an error code to the function.
*
*/
var xhr = {
errorCode: 'timeout',
callInProgress: function (xmlhttp) {
switch (xmlhttp.readyState) {
case 1: case 2: case 3:
return true;
// Case 4 and 0
default:
return false;
}
}
};
// Register global responders that will occur on all AJAX requests
Ajax.Responders.register({
onCreate: function (request) {
request.timeoutId = window.setTimeout(function () {
// If we have hit the timeout and the AJAX request is active, abort it and let the user know
if (xhr.callInProgress(request.transport)) {
var parameters = request.options.parameters;
request.transport.abort();
// Run the onFailure method if we set one up when creating the AJAX object
if (request.options.onFailure) {
request.options.onFailure(request.transport, xhr.errorCode, parameters);
}
}
},
// 10 seconds
10000);
},
onComplete: function (request) {
// Clear the timeout, the request completed ok
window.clearTimeout(request.timeoutId);
}
});
内容总结
以上是互联网集市为您收集整理的javascript – 在浏览器中检测离线模式的最佳方法是什么?全部内容,希望文章能够帮你解决javascript – 在浏览器中检测离线模式的最佳方法是什么?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。