mister martin
mister martin

Reputation: 6252

JQuery lazy loading doesn't always work

I have the following to lazy-load images:

$(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');
                }
            }
        });
    });
});

What I've noticed (at least in Chrome), however, is that sometimes the images won't initially load, but show up as soon as I start scrolling. Any idea why or what is wrong?

EDIT: here is a JSFiddle although reproducing the problem seems to be completely sporadic, I don't know what exactly causes it... Hence why I'm here.

Upvotes: 1

Views: 1496

Answers (1)

ccprog
ccprog

Reputation: 21811

You are calling $(window).on('load', fn) inside the $(document).ready callback. To quote the jQuery doc:

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.

Better execute the loader function once unconditionally:

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

Upvotes: 1

Related Questions