开发者

Test whether image loaded correctly with JavaScript

I have an image deployed on several application servers (green up arrow: uparrow.gif). I have an application server status page where I list out all the servers and with a corresponding image where the image's source is the uparrow.gif for that server. If the image does not load (server down) I would like to switch to a red down arrow (downarrow.gif). Is there a way to check whether an image loaded or not with straight JavaScript (no JS libraries etc)? I would imagine I would set an inte开发者_如何转开发rval for it to continue checking if the user were on the page.


var image = new Image();
image.onload = function() {
   // display green arrow
}
image.onerror = function() {
   // display red arrow
}
image.src = 'http://yourserver/test.gif';

EDIT:

With the images already in the HTML it becomes a bit tricky, because the onerror event is not part of HTML only of the DOM. Theoretically you could do something like this, if you don't mind invalid markup:

<img src="http://yourserver/up_arrow.png" onerror="this.src='down_arrow.png'">


Now StackOverflow can live up to its name. The following code gives a stackoverflow in IE but it SHOULD run. What is the issue? fix it and JOHKAR has a solution

<script>
var timeout = 600000; // 10 minutes 
var servers = {
server1:'//server1',
server2:'//server2'
} // not the lack of comma after the last iterm

var tIds = [];
function loadImage(id) {
  document.getElementById(id).src=servers[id]+'/on.gif?timestamp='+new Date().getTime(); // make sure it does not cache
}
window.onload=function() { 
  for(var server in servers){
    var img = document.createElement('img');
    img.id=server;    
    img.onload=function(){
      clearTimeout(tIds[this.id]); 
      tIds[this.id]=setTimeout("loadImage('"+this.id+"')",timeout); // run again in 10 minutes  
    } 
    img.onerror=function(){ 
      this.src="off.gif";
      this.title = 'server off at '+new Date();
      clearTimeout(tIds[this.id]); 
      tIds[this.id]=setTimeout("loadImage('"+this.id+"')",timeout); // run again in 10 minutes
    } // off cannot come from the broken server
    document.getElementById('imageContainer').appendChild(img);
    loadImage(server) 
  } 
}
</script>
<div id="imageContainer"></div>  


Your task of displaying red arrow for dead servers and showing green arrow for live ones is solvable with CSS only:<img src="http://server/greenarrow.gif" style="background:url(local/redarrow.gif)"/>. No need for javascript, the red arrow will be displayed by default and only if the server is up and running, the green arrow will be visible instead of red arrow.

But if you really want to go with js, then onerror event will help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜