JQuery 延迟加载并不总是有效



我有以下对懒惰的图像:

$(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中(是,有时图像最初不会 load ,但是一旦我开始滚动就会出现。知道为什么或什么错?

编辑:这是一个JSFIDDLE/div>

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

请注意,尽管DOM始终在页面满载之前就可以准备就绪,但是在.Dready((处理程序中执行的代码中附加载荷事件侦听器通常是不安全的。

最好一次无条件执行加载程序函数:

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

最新更新