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

yll*_*ate 15 html javascript css jquery ruby-on-rails

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

有没有办法检测图像是否加载失败然后如果是这样,在img src上重新加载直到它加载?如果是这样,你能举个例子吗?

Ash*_*raf 17

<img onerror="dosomthing()" ...>
Run Code Online (Sandbox Code Playgroud)

  • 那是'$('#myImg').bind('error',function(e){...});`在jQuery中:) (4认同)
  • “dosomthing()”应该怎么做来重新加载图像? (2认同)

Ram*_*din 9

这里我编译的内容可能有所帮助.我无法对此进行测试,如果您遇到任何问题请告诉我.

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

});
Run Code Online (Sandbox Code Playgroud)

上述解决方案是由@ user113716@travis开始的两种不同解决方案编译而成


小智 5

看看这段代码:

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

  • ...或者在错误函数中使用setTimeout不会让它像疯了一样重新加载. (2认同)