Search code examples
javascriptjqueryajaxlazy-loadingjquery-lazyload

jQuery.lazy() plugin not working on images loaded via AJAX


The lazy plugin works fine for the initially loaded elements but doesn't work for images loaded via AJAX despite having the code in done function of the AJAX call.

Here is my code for lazy loading images

jQuery(document).ready(function() {
    jQuery("img.lazy").lazy({
        effect: "fadeIn",
        effectTime: 1000
    });
});

Here is my AJAX call

$(document).ready(function() {
    $('#loadmore-dj').on('click', function() {
        $('#loadmore-dj').hide();
        $('#loadmore-dj-gif').css( "display", "block");
        $.ajax({
            type: "GET",
            url: "/loadmore/dj/",
            data: {
                'slug': $('.dj_slug').text().trim(),
                'song_rank': $("#dj_song_list").find('.song_block').length
            },
        }).done(function (response) {
            $(response).appendTo($('#dj_song_list')).hide().fadeIn(1000);
            playOneAudio();
            jQuery(document).ready(function() {
                jQuery("img.lazy").lazy({
                    effect: "fadeIn",
                    effectTime: 1000
                });
            });
            $('#loadmore-dj').show();
            $('#loadmore-dj-gif').hide();
        }).done(hideLoadMore);
    });
});

Solution

  • The problem was the missing scroll-event on the AJAX load with lazy by default. Adding the config parameter bind: "event" to lazy in my ajax function solved the issue.

    jQuery("img.lazy").lazy({
        effect: "fadeIn",
        effectTime: 1000,
        bind: "event"
    });