检测图像何时无法在 Javascript 中加载 [英] Detect when an image fails to load in Javascript

查看:26
本文介绍了检测图像何时无法在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆