如何检测图像加载失败,如果失败,尝试重新加载直到成功

How to detect image load failure and if fail, attempt reload until success?

本文关键字:加载 失败 新加载 成功 图像 何检测 如果 检测      更新时间:2023-09-26

我有一些图像从异地加载,无法控制它们的可用性。我发现,在重负载下,它们有时无法加载,但在快速刷新时,它们会立即显示出来。

有没有一种方法可以检测图像是否加载失败,如果是,则在img src上调用重载,直到加载为止?如果是,你能举一个例子吗?

<img onerror="dosomthing()" ...>

这里是我编译的一些可能会有所帮助的东西。我无法对此进行测试,如果您有任何问题,请告诉我。

$(function() {
   var $images = $('img.imageClassUpdateAtInterval:not([src="/assets/spinner.gif"])');
  // Now, no such image with
   // a spinner
   if($images.length === 0 && window.imageLocator)
     clearInterval(window.imageLocator);

    window.imageLocator = setInterval(function() {
        $images.each(function() {
            $this = $(this);
            if (!$this.data('src')) {
                $this.data('src', $this.prop('src'));
            }
            $this.prop('src', $this.data('src') + '?timestamp=' + new Date().getTime());
            console.log($this.prop('src'));
        });
    }, 60 * 1000);
   // suppose, an error occured during
   // locating the src (source) of the
   // image - image not found, network
   // unable to locate the resource etc.
   // it will fall in each time on error
   // occurred 
   $('img.imageClassUpdateAtInterval').error(
          function () {   
                 // set a broken image
                 $(this).unbind("error").attr("src", "/assets/broken.gif"); 
                 // setting this up in relative
                 // position
                 $(this).css("position", "relative");
                 $(this).apppend("<span>Error occured</span>");
                 $(this).find("span").css({"position": "absolute", "background-color": "#252525", "padding": ".3em", "bottom": "0"});
   });
});

上面的解决方案是由@user113716和@travis 开始的两个不同的解决方案编译的

看看这个代码:

$('img.autoFix').error(function(){
    var src = this.src;
    this.src = src.substr(0, src.indexOf('?')) + '?t=' + new Date().getTime()
});

在将其他答案中的一些想法与我自己的想法混合在一起后,我想出了一个对我有用的方法:

将其添加到img元素中:

onerror="tryAgain(this)"

脚本:

<script>  
  function tryAgain(e) 
  {
    setTimeout(reloadImg, 1000, e);
  }
  function reloadImg(e)
  {
    var source = e.src;
    e.src = source;
  }
</script>

当然,您可以将超时时间更改为您想要的任何时间。(请原谅我在回答中没有使用$;我是JS的新手,根本没有使用JQuery)。

这是一种非常简单的方法,可以处理页面上的所有图像。


https://github.com/doomhz/jQuery-Image-Reloader

jQuery Image Reloader

强制浏览器重新加载损坏的图像。对于存储在云中的图像(即AmazonS3),这是一个不错的解决方案。

为什么以及何时使用

当您从云(即Amazon S3)加载图像时,此插件是有效的,并且CDN会延迟到图像可访问为止。浏览器将显示一个损坏的图像图标,并且不会重试重新加载。jQuery image Reloader将处理此问题。

插件代码

激活插件所需的唯一代码是:

$(".slow-images").imageReloader();