Blog2011 ≫ Javascript ping

For work I needed to "ping" one website from another just using javascript - we have a customer on site A, and we want to send them to site B, but what if site B is broken? Let's send them somewhere else. So how do we tell if site B is up and running, and visible from where they are (in case, SAY, their DNS is broken). I found this1 and I adapted it to my needs like so:

var ping = { //2
  preload: null,
  timer: null,
  ping: function ( img, success, fail ) {
    var sess = new Date();
    var nocache = sess.getTime();
    var uri = img+"?time="+nocache;
    ping.preload = new Image();
    ping.preload.onload = function() {
        clearTimeout(ping.timer);
        ping.timer = null;
        success( img );
    };
    ping.preload.src = uri;
    ping.timer = setTimeout( function ( ) {
      clearTimeout( ping.timer );
      ping.timer = null;
      ping.preload = null;
      fail( img );
    }, 3000 );
  }
};

then to use it

ping.ping( 'http://foo.com', success_function, fail_function );

so something like

ping.ping( 'http://foo.com/img.png',
  function( img ) { alert( img + ' success' ) },
  function( img ) { alert( img + ' failed' ) }
);

js: Programming language of the web, mostly how I make my living.

⬅️ :: ➡️

Paul Clarke's weblog - I live in A small town. Married + dad to 2, I am a full-stack web developr, and I do javascript / nodejs, some ruby, python, php etc. I like pubbing, parkrun, eating, home automation + other diy jiggery-pokery, history, genealogy, Television, squirrels, pirates, lego, and time travel.