加载页面并完全下载图像后动态替换图像src

时间:2018-06-12 14:40:18

标签: jquery image lazy-loading

尝试创建一个简单的延迟图像加载,以便在加载页面并完全下载图像后用主项目图像替换默认图像。但是在jquery代码下面使用和错误。

HTML示例

<img src="default.png" data-src="image-1.png" class="productImage"/>
<img src="default.png" data-src="image-2.png" class="productImage"/>
<img src="default.png" data-src="image-3.png" class="productImage"/>
<img src="default.png" data-src="image-4.png" class="productImage"/>

Jquery示例

$(function(){
    $('img.productImage').each(function(){
       var this_image = this;
       var src = $(this_image).attr('src');
       var lsrc = $(this_image).attr('data-src');
        if(lsrc.length > 0){
            var img = new Image();
            img.src = lsrc;
            $(img).load(function() {
                this_image.src = this.src;
            });
        }else{
            this_image.src = src;
        }
    });
});

上述脚本会出现此错误TypeError: e.indexOf is not a function[Learn More] jquery-3.2.1.min.js:2:82466

我也尝试使用下面的代码并且它工作但是不太确定它在替换src之前是否等待图像下载,因为它总是替换一个页面加载。

$(function(){
    $('img.productImage').each(function(){
       var this_image = this;
       var src = $(this_image).attr('src');
       var lsrc = $(this_image).attr('data-src');
            if(lsrc.length > 0){
                this_image.src = lsrc;
            }else{
                this_image.src = src;
            }

    });
});

1 个答案:

答案 0 :(得分:0)

load不是.on("load"的快捷方式,它完全不同(从服务器加载HTML并将其放入元素中)。另外,在设置load之前,始终挂钩src事件,而不是之后,以避免竞争条件。

var img = new Image();
$(img).on("load", function() {
    this_image.src = this.src;
});
img.src = lsrc;

使用on代替load解决了奇怪的url.indexOf(缩小版本中的e.indexOf)错误:

$(function(){
    $('img.productImage').each(function(){
       var this_image = this;
       var src = $(this_image).attr('src');
       var lsrc = $(this_image).attr('data-src');
       if(lsrc.length > 0){
            var img = new Image();
            $(img).on("load", function() {
                this_image.src = this.src;
            });
            img.src = lsrc;
        }else{
            this_image.src = src;
        }
    });
});
<img src="http://via.placeholder.com/100x100?text=p" data-src="http://via.placeholder.com/100x100/08f/000?text=1" class="productImage"/>
<img src="http://via.placeholder.com/100x100?text=p" data-src="http://via.placeholder.com/100x100/08f/000?text=2" class="productImage"/>
<img src="http://via.placeholder.com/100x100?text=p" data-src="http://via.placeholder.com/100x100/08f/000?text=3" class="productImage"/>
<img src="http://via.placeholder.com/100x100?text=p" data-src="http://via.placeholder.com/100x100/08f/000?text=4" class="productImage"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>