faqts : Computers : Programming : Languages : JavaScript : Event handling

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

113 of 151 people (75%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

Can I check with client side JavaScript whether a http server is up?
Can I check with client side JavaScript whether a http server is up?
Can I check with client side JavaScript whether a http server is up?

Mar 19th, 2000 10:32
Martin Honnen,


Client side Javascript has no means to ping an internet host and it 
can't directly check whether a http server is responding or whether a 
url exists. It has however (starting with js 1.1) the Image object with 
two event handlers
  onload
and 
  onerror
which you can use to check whether an image from a server is loadable 
and react to it. So if you are are able to place content on a http 
server you can place a (small) test image on it which you try to load 
to find out whether the server is currently up and responding to web 
requests. If the onload handler of the image fires the server is up and 
reachable and you can load other content from it, if the onerror 
handler fires you do something else (load content from another server 
for instance). 
The following is an example which assumes that two servers
  javascript1.faqts.com
and
  javascript2.faqts.com
exist and tries to load a test image from them. As these servers don't 
exists the default action namely accessing 
  javascript.faqts.com
is always executed but the example serves to demonstrate the use of 
Image onerror/onload for server checking.

<HTML>
<HEAD>

<SCRIPT>
function errorHandler (evt) {
  if (this.src.indexOf('javascript1') != -1)
    // error with javascript1, check next host
    this.src = 'http://javascript2.faqts.com/testimg.gif';
  else if (this.src.indexOf('javascript2') != -1)
    // error with javascript2, load default host
    location.href = 'http://javascript.faqts.com/';
}
function loadHandler (evt) {
  if (this.src.indexOf('javascript1') != -1)
    location.href = 'http://javascript1.faqts.com/'; 
  else if (this.src.indexOf('javascript2') != -1)
    location.href = 'http://javascript2.faqts.com';
}
var img = new Image();
img.onload = loadHandler;
img.onerror = errorHandler;
img.src = 'http://javascript1.faqts.com/testimg.gif';
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>