Snippet – Checking Internet Connection, No More Hanging App

Messaging-Online-iconWhen you are writing your single page application (SPA) may find that you need to check your connection. The idea is that you might have one set of logic for your connected app and another for when you are disconnected.

In previous posts, AppCache for Offline Apps and Loading, Caching LoDash or Underscore Templates Using RequireJS, AppCache, you learned that your Web app did not have to be online to be run. In fact, when building HTML apps for mobile devices, you are running without a connection.

So how do you check? How do you know when you can upload and download new information from the Web?

Many of the comments on StackOverflow have to do with the connection hanging. The following snippets help you work around the issue.

jQuery

6327_image_58FAEDFAYou can add a parameter to your jQuery AJAX calls so that it will include the use case where the remote URL is not reachable, but jQuery hangs and does not call its success or error functions.

The fix is to add a timeout, as shown on line 5:

Using XMLHttpRequest

W3CIf instead you just want a quick way to see if your app is connected, you can use XMLHttpRequest object’s open method.

In Microsoft Internet Explorer 6 and earlier, XMLHTTP was implemented as an ActiveX object provided by Microsoft XML (MSXML). Beginning with Internet Explorer 7, XMLHTTP is also exposed as a native scripting object.

If you need to support IE6, you can build your XMLHttpRequest object using the following code.

And you can substitute XMLHttpRequest in the previous example with your new xmlHttp object.

References

Advertisements