JQuery延迟加载并不总是有效

时间:2017-06-02 17:01:58

标签: javascript jquery lazy-loading

我有以下懒加载图片:

$(document).ready(function() {
    // lazy load images
    var win = $(window);
    win.on('load resize scroll', function() {
        var viewport = {
            top: win.scrollTop(),
            left: win.scrollLeft()
        };
        viewport.right = viewport.left + win.width();
        viewport.bottom = viewport.top + win.height();

        // cycle through all images (within visible content) and update src attributes
        $('img[data-src]').each(function() {
            var bounds = $(this).offset();
            bounds.right = bounds.left + $(this).outerWidth();
            bounds.bottom = bounds.top + $(this).outerHeight();

            // if image is within viewable area, display it
            if (!(viewport.right < bounds.left || viewport.left > bounds.right ||
                  viewport.bottom < bounds.top || viewport.top > bounds.bottom)) {
                var img = $(this).attr('data-src');
                if (img) {
                    $(this).attr('src', img);
                    $(this).removeAttr('data-src');
                }
            }
        });
    });
});

我注意到(至少在Chrome中),有时候图片最初加载,但是一旦我开始滚动就会显示出来。知道为什么或出了什么问题?

编辑:这里是JSFiddle虽然复制问题似乎是完全零星的,但我不知道究竟是什么导致它...因此为什么我&#39;我在这里。

1 个答案:

答案 0 :(得分:1)

您正在$(window).on('load', fn)回调中呼叫$(document).ready。引用jQuery doc:

  

请注意,虽然DOM在页面完全加载之前总是准备就绪,但在.ready()处理程序执行的代码中附加加载事件侦听器通常是不安全的。

无条件地更好地执行加载器功能:

$(document).ready(function() {
    var win = $(window);
    function lazyload () {
        //...
    }
    win.on('resize scroll', lazyload);
    lazyload();
});
相关问题