如何检测图像加载失败,如果失败,请尝试重新加载直到成功? [英] How to detect image load failure and if fail, attempt reload until success?

查看:194
本文介绍了如何检测图像加载失败,如果失败,请尝试重新加载直到成功?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

有没有一种方法可以检测图像是否无法加载,然后检测是否重新加载img src直到加载?如果是这样,请您举个例子吗?

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?

推荐答案

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

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

});

上述解决方案是由 @ user113716 @travis

这篇关于如何检测图像加载失败,如果失败,请尝试重新加载直到成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆