JQuery 延迟加载并不总是有效

JQuery lazy loading doesn't always work

我有以下延迟加载图像的方法:

$(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 虽然重现问题似乎完全是零星的,但我不知道到底是什么原因造成的...因此我为什么来了。

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

Note that although the DOM always becomes ready before the page is fully loaded, it is usually not safe to attach a load event listener in code executed during a .ready() handler.

最好无条件执行一次loader函数:

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