0

I currently have an image which gets pinged in order to only show a div if the local content is available.

But I think a better implementation is to periodically check for ping, at a 30 second interval, then show an #offline div if the image has not been pinged successfully. This is better as it considers that the status of the connection may change without the page having been reloaded.

Original script:

function ImgLoad(myobj){
   var randomNum = Date.now() || new Date().getTime();
   var oImg=new Image;
   oImg.src="http://192.168.8.1/images/ping2.jpg"+"?rand="+randomNum;
   oImg.onload=function(){$("#online").show();}

}

I think I have managed to get the function to poll every 30 seconds, but I've not been able to show a div on error rather than if it pings successfully.

function checkping(){
function ImgLoad(myobj){
   var randomNum = Date.now() || new Date().getTime();
   var oImg=new Image;
   oImg.src="http://192.168.8.1/images/ping2.jpg"+"?rand="+randomNum;
   oImg.onload=function(){$("#online").show();}

}
}

setInterval(function(){
checkping()}, 30000)
gjames
  • 149
  • 1
  • 5
  • Possible duplicate of [jQuery/JavaScript to replace broken images](https://stackoverflow.com/questions/92720/jquery-javascript-to-replace-broken-images) – vahdet Jan 26 '18 at 11:56

2 Answers2

1

I've not been able to show a div on error

You're already using .onload, just use the corresponding .onerror :

oImg.onerror=function(){$("#error").show();}
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
0

Maybe consider "smart" polling instead, which checks your server for the image on incrementally increasing intervals instead of a fixed one.

This link may be of aide: https://github.com/blog/467-smart-js-polling

Tarek
  • 1,219
  • 13
  • 18