Skip to content

Instantly share code, notes, and snippets.

@khalidsalomao
Last active October 7, 2016 16:23
Show Gist options
  • Save khalidsalomao/81aa293b6b6ac7a9d8679b8991c2ee41 to your computer and use it in GitHub Desktop.
Save khalidsalomao/81aa293b6b6ac7a9d8679b8991c2ee41 to your computer and use it in GitHub Desktop.
function checkConnection(callback, timeout) {
var checkStatus = function() {
report((xhr.status && xhr.status < 12000) ? 'up' : 'down');
};
var last = '';
var report = function(status){
if (status !== last){
last = status;
callback(status === 'up');
}
};
var url = "//" + window.location.hostname + "/?_=" + (new Date()).getTime();
var xhr = new XMLHttpRequest();
xhr.timeout = timeout || 2000;
if (xhr.onprogress === null) {
xhr.onload = checkStatus;
xhr.onerror = checkStatus;
xhr.ontimeout = checkStatus;
} else {
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
checkStatus();
} else if (xhr.readyState === 0) {
report('down');
}
};
}
try {
xhr.open("HEAD", url);
xhr.send();
} catch (error) {
report('down');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment