使用JavaScript测试图像是否正确加载 [英] Test whether image loaded correctly with JavaScript
问题描述
我在多个应用程序服务器上部署了一个映像(绿色向上箭头:uparrow.gif)。我有一个应用程序服务器状态页面,其中列出了所有服务器以及相应的图像,其中图像的源是该服务器的uparrow.gif。如果图像没有加载(服务器关闭),我想切换到红色向下箭头(downarrow.gif)。有没有办法检查是否加载了直接JavaScript(没有JS库等)的图像?我想我会设置一个间隔,让它继续检查用户是否在页面上。谢谢。
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 interval for it to continue checking if the user were on the page. Thanks.
推荐答案
var image = new Image();
image.onload = function() {
// display green arrow
}
image.onerror = function() {
// display red arrow
}
image.src = 'http://yourserver/test.gif';
编辑:
由于HTML中已有图像,因此onerror事件不仅仅是DOM的HTML的一部分。从理论上讲,如果你不介意无效标记,你可以这样做:
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'">
这篇关于使用JavaScript测试图像是否正确加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!