检测图像何时无法在Javascript中加载

sazr:

有没有一种方法可以确定图像路径是否指向实际图像,即检测图像何时无法在Javascript中加载。

对于Web应用程序,我正在解析xml文件,并根据图像路径列表动态创建HTML图像。服务器上可能不再存在某些图像路径,因此我想通过检测哪些图像无法加载并删除该HTML img元素来正常地失败。

注意JQuery解决方案将无法使用(老板不想使用JQuery,是的,我知道不要入门)。我知道在JQuery中一种检测何时加载图像的方法,但不知道它是否失败。

我创建img元素的代码,但是如何检测img路径是否导致无法加载图像?

var imgObj = new Image();  // document.createElement("img");
imgObj.src = src;
尼基尔:

您可以尝试以下代码。不过,我不能保证浏览器的兼容性,因此您必须进行测试。

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的老板表示同情!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章