Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

jquery - Binding image lazy loading to new images inserted after ajax request

I'm using Mika Tuupola's Lazy Load plugin http://www.appelsiini.net/projects/lazyload to delay loading images as you scroll down a long image gallery. The problem is after 10 images, I use infinite scrolling so I fetch the next 10 images, and append them via ajax. Lazy Loading no longer works on this next batch of appended images.

It's a pretty javascript-heavy image gallery, so for everything else (such as tooltips, modal overlays, etc) I've been using jQuery's delegate() to bind to ajax-inserted elements. The problem with the Lazy Load plugin is that I'm not sure what event to bind to.

So say I want to lazy load images with a class of "lazy". I would write this:

$("img.lazy").lazyload({ 
    effect: "fadeIn" 
});

and it works for the first 10 images, but stops working after inserting more via ajax. The only thing I can think of is to use delegate on a load event, like so:

$(document).delegate("img.lazy", "load", function(event) {  
    $(this).lazyload({ 
         effect: "fadeIn" 
    });     
});

but that breaks everything. Thanks!

EDIT: The jQuery I use to load more records (this is a Rails app):

$(window).scroll(function() {
    var url;
    url = $(".pagination .next_page").attr("href");
    if (url && $(window).scrollTop() > $(document).height() - $(window).height() - 50) {
    $(".pagination").html("<p>loading more images...</p>");
    return $.getScript(url);
    }
});

$(window).scroll();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would use the ajaxStop method.

$("img.lazy").lazyload({ 
    effect: "fadeIn" 
}).removeClass("lazy");
$(document).ajaxStop(function(){
    $("img.lazy").lazyload({ 
        effect: "fadeIn" 
    }).removeClass("lazy");
});

removeClass prevents double initialization.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...