Check if the image is loaded correctly with JavaScript
I have an image deployed to multiple application servers (green arrow: uparrow.gif). I have an application server status page where I list all servers and the corresponding image, where the image source is uparrow.gif for that server. If the image doesn't load (server down), I would like to switch to the red down arrow (downarrow.gif). Is there a way to check if the image is loaded or not with straight JavaScript (no JS libraries, etc.)? I would guess that I would set an interval to continue checking if the user is on the page. Thanks.
a source to share
var image = new Image();
image.onload = function() {
// display green arrow
}
image.onerror = function() {
// display red arrow
}
image.src = 'http://yourserver/test.gif';
EDIT:
With images already in HTML, this gets a little trickier because the onerror event is not part of the HTML just from the DOM. In theory, 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'">
a source to share
Now StackOverflow can live up to its name. The following code gives a stack thread in IE, but it MUST start. What is the problem? 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>
a source to share
Your task is to display the red arrow to the dead server and display the green arrow to live, is only permitted using the CSS: <img src="http://server/greenarrow.gif" style="background:url(local/redarrow.gif)"/>
. No javascript needed, a red arrow will be displayed by default and only if the server is up and running will the green arrow be visible instead of the red arrow.
But if you really want to go with js then event onerror
will help.
a source to share