在javascript中检查Internet连接的最佳实践

时间:2012-05-16 10:32:33

标签: javascript ajax internet-explorer internet-connection

我正在使用Ajax在我的应用程序使用IE实例的每几秒后检查我的Internet连接。但由于带宽较低,我的Internet Explorer正在崩溃。

可以遵循哪些最佳做法来检查互联网连接,以防止Internet Explorer崩溃并提升性能?

我使用以下代码检查我的互联网连接。

其解释见: -

http://tomriley.net/blog/archives/111我从哪里得到jquery文件。

(function ($) {

      $.fn.checkNet = function (intCheckInterval, strCheckURL) {
          if (typeof (intCheckInterval) === 'undefined') {
              var intCheckInterval = 5
          } if (typeof (strCheckURL) === 'undefined') {
              var strCheckURL = window.location
          } else if (strCheckURL.indexOf('http') === -1) {
              var strCheckURL = 'http://' + strCheckURL
          } intCheckInterval = intCheckInterval * 1000; function doRequest(strCheckURL) {
              $.ajax({ url: strCheckURL, cache: false, success: function () {
                  if ($('#netWarn').length) {
                      $('#netWarn').fadeOut()
                  } $('.tempDisabled').removeAttr('disabled').removeClass('tempDisabled')
              }, error: function () {
                  if (!$('#netWarn').length) {


                      $('body').prepend('<p id="netWarn">No internet connection detected, some features will be re-enabled when a connection is detected. </p>'); $('#netWarn').fadeIn()

                  }

              }
              })
          } setInterval(function () {
              doRequest(strCheckURL)
          }, intCheckInterval)
      }
})(jQuery);  

1 个答案:

答案 0 :(得分:0)

我的插件接受请求之间的时间长度的参数。因此,如果您希望请求之间有10秒的间隔,请使用以下代码调用它:

$.fn.checkNet(10);

...在您加入插件后...我最近上传了一个新版本,效率更高。