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.


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:

type : "GET",
url : "",
data : params,
timeout: 3000,
dataType : "json",
jsonp : "json",
success : function (response, textS, xhr) {
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("not ok " + errorThrown);
alert("request timed out");

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.

function check() {
var z, xml = null;
xml = new XMLHttpRequest();
// use xmlHttp object shown in the next snippet if you need to support IE6
// xml = new xmlHttp"get", url, false);
try {
} catch(z) {
alert("Network failure");
if ((xml.status >= 200 && xml.status <= 300) || xml.status == 304) {
var hi = xml.responseText;
} else {
alert("No Internet Connection! You will have to enter information by hand");

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.

var xmlHttp = null;
if (window.XMLHttpRequest) {
// If IE7, Mozilla, Safari, and so on: Use native object.
xmlHttp = new XMLHttpRequest();
if (window.ActiveXObject) {
// …otherwise, use the ActiveX control for IE5.x and IE6.
xmlHttp = new ActiveXObject('MSXML2.XMLHTTP.3.0');

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