检测何时无法在Javascript中加载图像 [英] Detect when an image fails to load in Javascript
问题描述
有没有办法确定图像路径是否会导致实际图像,即检测到图像无法在Javascript中加载。
Is there a way to determine if a image path leads to an actual image, Ie, detect when an image fails to load in Javascript.
对于Web应用程序,我正在解析一个xml文件,并从图像路径列表中动态创建HTML图像。服务器上可能不再存在某些图像路径,因此我希望通过检测哪些图像无法加载并删除该HTML img元素来优雅地失败。
For a web app, I am parsing a xml file and dynamically creating HTML images from a list of image paths. Some image paths may no longer exist on the server so I want to fail gracefully by detecting which images fail to load and deleting that HTML img element.
注意JQuery解决方案不会能够被使用(老板不想使用JQuery,是的,我知道不要让我开始)。我知道JQuery中有一种方法可以检测图像的加载时间,但不知道它是否失败。
Note JQuery solutions wont be able to be used(the boss doesn't want to use JQuery, yes I know dont get me started). I know of a way in JQuery to detect when an image is loaded, but not whether it failed.
我创建img元素的代码但是如何检测img路径导致无法加载图片?
My code to create img elements but how can I detect if the img path leads to a failed to load image?
var imgObj = new Image(); // document.createElement("img");
imgObj.src = src;
推荐答案
您可以尝试以下代码。我不能担保浏览器兼容性,所以你必须测试它。
You could try the following code. I can't vouch for browser compatibility though, so you'll have to test that.
function testImage(URL) {
var tester=new Image();
tester.onload=imageFound;
tester.onerror=imageNotFound;
tester.src=URL;
}
function imageFound() {
alert('That image is found and loaded');
}
function imageNotFound() {
alert('That image was not found.');
}
testImage("http://foo.com/bar.jpg");
我对jQuery抗拒老板的同情!
And my sympathies for the jQuery-resistant boss!
这篇关于检测何时无法在Javascript中加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!