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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8968576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:10:14  来源:igfitidea点击:

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

javascriptjqueryhtmlruby-on-railscss

提问by ylluminate

I have some images loading from offsite and have no control over their availability. I've found that under heavy load they are sometimes failing to load, but on a quick refresh they'll show right up.

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

Is there a way to detect if images fail to load and then if so, evoke a reload on the img src until it loads? If so, could you please provide an example?

有没有办法检测图像是否无法加载,如果是,则在 img src 上重新加载直到加载?如果是这样,你能提供一个例子吗?

采纳答案by Ramiz Uddin

Here something I compiled which might help. I couldn't manage to do testing of this please let me know if you are having any issues.

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

$(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"});
   });

});

The above solution is compiled from two different solutions commenced by @user113716and @travis

上述解决方案由@user113716@travis 提出的两种不同的解决方案编译而来

回答by Ashraf

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

回答by Kiyan

take a look at this code:

看看这段代码:

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

回答by MockWhy

This a very simple approach that handles all images on the page.

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



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

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

jQuery Image Reloader

jQuery 图像重载器

Forces the browser to retry loading the broken images. A decent solution for images stored in a cloud (i.e Amazon S3).

强制浏览器重试加载损坏的图像。存储在云中的图像的体面解决方案(即 Amazon S3)。

Why and when to use it?

为什么以及何时使用它?

This plugin is effective when you load images from a cloud (i.e. Amazon S3) and the CDN has a delay until the image is accessible. The browser will display a broken image icon instead and won't retry to reload it. jQuery Image Reloader will take care of that.

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

Plugin code

插件代码

The only code you need to activate the plugin is this:

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

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

回答by JCamacho

After mixing together a few ideas from other answers, along with my own, I came up with something that worked for me:

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

Add this to your img elements:

将此添加到您的 img 元素:

onerror="tryAgain(this)"

Script:

脚本:

<script>  
  function tryAgain(e) 
  {
    setTimeout(reloadImg, 1000, e);
  }

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

You can of course change the timeout to whatever you want. (forgive me for not using $ in my answer; I'm new to JS and haven't used JQuery at all).

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