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 this 1 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' ) }
);
⬅️ Cider diary :: Our new bed is on the way! ➡️
Paulʼs blog - I live some place you've not heard of near Folkestone, Kent. Married + father to 2, I am a full stack web engineer, + I do js / node, some ruby, other languages etc. My hobbies are pubs, parkrun, restaurants, home automation 🤖 and other diy jiggery-pokery, history, tree stuff, TV, squirrels, pirates ☠️, lego, + TIME TRAVEL.