代码之家  ›  专栏  ›  技术社区  ›  Andrew

如何判断图像是否正确加载

  •  2
  • Andrew  · 技术社区  · 15 年前

    有没有办法在事后判断一个图像(放置在 <img> 标签,而不是通过JS)已正确加载到页面中?我有一个头部照片库,偶尔第三方图像服务器会提供404。我可以将服务器端代码更改为使用 onerror="showGenericHeadshot()" ,但我确实希望避免对服务器端代码进行更改。最后,我想确定一个图像是否丢失或损坏,并用一个通用的“未找到图像”图形替换它。我尝试过的事情:

    1. Image.prototype.onerror = showGenericHeadshot <img> 标签
    2. $('img[src*=thirdpartyserver.com]).error(showGenericHeadshot)
    3. $('img[src*=thirdpartyserver.com]).css('backgroundImage','url(replacementimage.gif)') --工作,但仍然无法摆脱IE中损坏的图像图标
    4 回复  |  直到 15 年前
        1
  •  2
  •   Praveen Prasad    15 年前
    <img scr='someUrl' id="testImage" />
    
    jQuery('#testImage').bind('load',function(){
             alert ('iamge loaded');
    });
    

    为了避免竞争状况,请执行以下操作

    <img _src="http://www.caregiving.org/intcaregiving/flags/UK.gif" />
    // i have added an underscore character before src
    
    
    
    jQuery('img').each(function(){
            var _elm=jQuery(this);
            _elm.bind('load',_imageLoaded).attr('src',_elm.attr('_src'))
        });
    
        function _imageLoaded()
        {
            alert('img loaded');
        }
    
        2
  •  2
  •   Andrew    15 年前

    不幸的是,我不能接受@TJ Crowder和@Praveen的优秀答案,尽管两者都执行了所需的图像替换。@Praveen的答案需要对HTML进行更改(在这种情况下,我应该直接挂接到 <img> tag自己的 error=""

    @danp对我的问题的评论中提到的这个问题实际上已经为我找到了答案,尽管它并不是公认的答案。我能够确认它与ie7&8、FF和webkit浏览器一起工作。我怀疑它是否适用于较旧的浏览器,所以我有一个 try/catch

    $(function() {
        $('img[src*=images.3rdparty.com]').each(
            function() {
                try {
                    if (!this.complete || (!$.browser.msie && (typeof this.naturalWidth == "undefined" || this.naturalWidth == 0))) {
                        this.src = 'http://myserver.com/images/no_photo.gif';
                    }
                } catch(e) {}
            }
        );
    });
    
        3
  •  1
  •   GôTô    15 年前

    另一个文本是否足够?如果是这样,您可以使用img标记的alt属性。

        4
  •  1
  •   T.J. Crowder    15 年前

    我想我已经做到了:当DOM被加载时(甚至在 window.load 事件-毕竟,如果您希望在所有图像都尽可能完整时执行此操作,则可以通过创建一个新图像来追溯检查图像是否正常 img 元素,钩住它的 load error 事件,然后通过抓住 src live example ). 这段代码只是被冲掉了,这不是产品质量的问题——例如,您可能需要一个超时时间,如果您没有收到任何一个 负载 ,假设错误。(您可能需要替换棋盘格图像才能可靠地处理该问题。)

    此技术假定重用 src公司 重新加载图像,我认为这是一个相当可靠的假设(这当然是一个简单的假设) 可测试的 一)因为这项技术一直被用于预处理图像。

    jQuery(function($) {
        var imgs, checker, index, start;
    
        // Obviously, adjust this selector to match just your headshots
        imgs = $('img');
    
        if (imgs.length > 0) {
            // Create the checker, hide it, and append it
            checker = $("<img>").hide().appendTo(document.body);
    
            // Hook it up
            checker.load(imageLoaded).error(imageFailed);
    
            // Start our loop
            index = 0;
            display("Verifying");
            start = now();
            verify();
        }
    
        function now() {
            return +new Date();
        }
    
        function verify() {
            if (!imgs || index >= imgs.length) {
                display("Done verifying, total time = " + (now() - start) + "ms");
                checker.remove();
                checker = undefined;
                return;
            }
            checker[0].src = imgs[index].src;
        }
    
        function imageLoaded() {
            display("Image " + index + " loaded successfully");
            ++index;
            verify();
        }
    
        function imageFailed() {
            display("Image " + index + " failed");
            ++index;
            verify();
        }
    
        function display(msg) {
            $("<p>" + now() + ": " + msg + "</p>").appendTo(document.body);
        }
    });​
    

    Live example

    推荐文章