延迟加载背景图片,删除data-src onload

时间:2018-08-08 09:55:41

标签: jquery

我正在尝试在页面上延迟加载几个背景图像。我正在从数据属性data-src拍摄背景图像。加载图片后,我想删除data-src数据属性:

$(window).on('load', function() {

    $.fn.loadbgimg = function () {
        $('.jumbo[data-src]').each(function(index) {

            var top_of_object = $(this).offset().top;
            var bottom_of_window = $(window).scrollTop() + $(window).height();

            /* If the object in the window */
            if( bottom_of_window > top_of_object ) {   

                // get datasrc  
                datasrc = $(this).data('src'); 

                // replace bg with data-src
                $(this).css("background-image", "url('" + datasrc + "')"); 

                // remove data-src when img loaded
                $(this).on('load', function() {

                   $(this).removeAttr('data-src');

                });


            }
        });
    };

    $('.jumbo').loadbgimg();

    /* Every time the window is scrolled ... */
    $(window).scroll( function(){

        $('.jumbo').loadbgimg();

    });

});

除了最后一部分“加载img时删除data-src”之外,其他所有内容似乎都可以正常工作。这什么也没做。数据属性未删除。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

背景图片没有加载事件。解决此问题的通常方法是创建一个图像元素,不要将其添加到DOM中,而是设置src属性。然后处理该事件的加载事件,并在加载事件后设置背景图片网址。因为您已经加载了图像,它将使用您的缓存,而不是再次下载它。您可以在那时删除data-src属性。

这是一个例子...

var $this = $(this);
var datasrc = $this.data('src'); 

// create an image so we have something with a load event
var $img = $("<img/>");

// handle the load event - remove the data-src attribute
$img.on("load", function() {

    // replace bg with data-src
    $this.css("background-image", "url('" + datasrc + "')"); 

    // remove data-src when img loaded
    $this.removeAttr('data-src');
});

// load the image in memory
$img.attr("src", datasrc);
相关问题