img error 图片加载失败的最佳方案

有时候, 当img的src加载失败, 会显示缺省碎片图片,  影响用户体验。  有一个js事件onerror就派上了用场。 它可以在加载失败时, 显示缺省的图片。 

它有两种使用方式。 

第一种: 使用纯标签写法。 这样会增大网页的体积。  但是客户端解析速度要快点。 

<img src="https://www.88tv.org/upload/vod/20190829-1/db8b269c40172799f215aba93f03a03d.jpg" onerror="javascript:this.src='https://t.8kmm.com/upload/vod/20190829-1/db8b269c40172799f215aba93f03a03d.jpg';">

第二种:使用Jquery JS, 全站如果有规律, 可以使用此种方式。  在所需页面插入下面这段js就行了。 

<script>
$(document).ready(function(){  
    $('.stui-vodlist img').each(function(){   //我这里仅仅是遍历vodlist这个元素下面的内容。 
        var error = false;
        if (!this.complete) {
            error = true;
        }

        if (typeof this.naturalWidth != "undefined" && this.naturalWidth == 0) {
            error = true;
        }

        if(error){
            $(this).bind('error.replaceSrc',function(){
                this.src = this.src.replace("www.88tv.org","t.8kmm.com");  //注意这一句,  因为这里是有规律的, 所有我可以这样写,如果有不同, 这里需要定制。 

                $(this).unbind('error.replaceSrc');
            }).trigger('load');
        }
    });
});
</script>

结尾:

如果碰到onerror过去的图片也没有, 可能会造成循环请求, 这样的话, 就需要对这段升级。 

 可以使用, 去检查图片是否存在, 

var imgUrl = "https://t.8kmm.com/upload/vod/20191006-16/d9823993b55e8cb504cf174c7bd9db12.jpg";
        var img = new Image();
        img.src=imgUrl;
        //判断图片大小是否大于0 或者 图片高度与宽度都大于0
        if(img.filesize>0||(img.width>0&&img.height>0)){
            e.src = imgUrl;
        }else{
            //默认图片也不存在的时候
            e.src="/img/default.jpg";
        }

当然, 也可以使用XMLHTTP远程判断图片是否存在。再根据远程获取的是404还是200来更换图片SRC。 

原文地址:https://www.cnblogs.com/jackrebel/p/11895991.html