我有一个网页,里面有很多图片。有时映像不可用,因此在客户机的浏览器中显示一个损坏的映像。

我如何使用jQuery来获取图像集,过滤它到破碎的图像,然后替换src?


—我本以为用jQuery会更容易做到这一点,但事实证明使用纯JavaScript解决方案更容易,也就是Prestaul提供的解决方案。


当前回答

我找不到适合我需要的脚本,所以我做了一个递归函数来检查损坏的图像,并尝试每四秒重新加载它们,直到它们修复。

我将它限制为10次尝试,因为如果它没有加载,那么图像可能不会出现在服务器上,函数将进入一个无限循环。不过我仍在测试中。请随意调整它:)

var retries = 0;
$.imgReload = function() {
    var loaded = 1;

    $("img").each(function() {
        if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {

            var src = $(this).attr("src");
            var date = new Date();
            $(this).attr("src", src + "?v=" + date.getTime()); //slightly change url to prevent loading from cache
            loaded =0;
        }
    });

    retries +=1;
    if (retries < 10) { // If after 10 retries error images are not fixed maybe because they
                        // are not present on server, the recursion will break the loop
        if (loaded == 0) {
            setTimeout('$.imgReload()',4000); // I think 4 seconds is enough to load a small image (<50k) from a slow server
        }
        // All images have been loaded
        else {
            // alert("images loaded");
        }
    }
    // If error images cannot be loaded  after 10 retries
    else {
        // alert("recursion exceeded");
    }
}

jQuery(document).ready(function() {
    setTimeout('$.imgReload()',5000);
});

其他回答

如果有人像我一样,试图将错误事件附加到动态HTML img标记,我想指出的是,有一个陷阱:

显然,img错误事件不会在大多数浏览器中冒泡,这与标准的说法相反。

所以,像下面这样的代码是行不通的:

$(document).on('error', 'img', function () { ... })

希望这对其他人有所帮助。我希望我能在这个帖子里看到这个。但是,我没有。我把它加起来

这里有一个独立的解决方案:

$(window).load(function() {
  $('img').each(function() {
    if ( !this.complete
    ||   typeof this.naturalWidth == "undefined"
    ||   this.naturalWidth == 0                  ) {
      // image was broken, replace with your new image
      this.src = 'http://www.tranism.com/weblog/images/broken_ipod.gif';
    }
  });
});

我不确定是否有更好的方法,但我可以想到一个hack来获得它-你可以Ajax post到img URL,并解析响应,看看图像是否真的回来了。如果返回404或其他错误,则更换img。不过我估计过程会很缓慢。

更好的呼叫使用

jQuery(window).load(function(){
    $.imgReload();
});

因为使用文档。ready并不一定意味着图像被加载,只是HTML。因此,不需要延迟调用。

对于React开发者:

<img 
    src={"https://urlto/yourimage.png"} // <--- If this image src fail to load, onError function will be called, where you can add placeholder image or any image you want to load
    width={200} 
    alt={"Image"} 
    onError={(event) => {
       event.target.onerror = "";
       event.target.src = "anyplaceholderimageUrlorPath"
       return true;
    }}
 />