What’s the fastest way to check if my server is online via JavaScript?
I’ve tried the following AJAX:
function isonline() {
var uri = 'MYURL'
var xhr = new XMLHttpRequest();
xhr.open("GET",uri,false);
xhr.send(null);
if(xhr.status == 200) {
//is online
return xhr.responseText;
}
else {
//is offline
return null;
}
}
The problem is, it never returns if the server is offline. How can I set a timeout so that if it isn’t returning after a certain amount of time, I can assume it is offline?
XMLHttpRequestdoes not work cross-domain. Instead, I’d load a tiny<img>that you expect to come back quickly and watch theonloadevent:Edit: Cleaning up my answer. An
XMLHttpRequestsolution is possible on the same domain, but if you just want to test to see if the server is online, the img load solution is simplest. There’s no need to mess with timeouts. If you want to make the code look like it’s synchronous, here’s some syntactic sugar for you: