Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery lazyload with ajax

I use lazyload() on my ecommerce website. lazyload() works great. I use this code to do that:

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

Also there are some filter like color, price etc. which is run an ajax and show new result. When new result come, lazyload() doesn't work. I know that I have to use lazyload() with live(), delegate() or on(). But I am a newbie on jquery and I couldn't do that. Can anyone help me please? My jquery version is 1.7.2 and we can use on().

like image 235
tebdilikiyafet Avatar asked Dec 09 '12 20:12

tebdilikiyafet


2 Answers

Shortly, the best optimized way to do this is to call the lazyload in your ajax's success function:

$.ajax({
    url: "your url here",
    type: "Post",
    success: function(response){
        // handle your success callback here
        $("img.lazy").lazyload({ 
              effect : "fadeIn"
        });
    }
});

But if you want to centralize your call to the lazyload plugin, you have 2 options:

First: (not recommended due to performance hit)

$(document).on('DOMNodeInserted', '#container', function() {
    $("img.lazy").lazyload({
        effect: 'fadeIn'
    });
});

but note here the "#container", it is the container's selector where you will show your new loaded stuff, so the code above will listen inside this container for any newly added stuff to run the lazyload again on new images,

Second: (recommended)

Calling your custom lazyload by adding it to your JQuery:

$.fn.myLazyLoad = function() {
    this.lazyload({ 
          effect : "fadeIn"
    });
};

then, call it in all your AJAX requests:

$.ajax({
    url: "your url here",
    type: "Post",
    success: function(response){
        // handle your success callback here
        $("img.lazy").myLazyLoad();
    }
});
like image 167
AbdelHady Avatar answered Sep 24 '22 20:09

AbdelHady


NOTE: At the time this answer was accepted, this worked. The lazy loading plugin changed and now it is broken. I cannot unaccept the answer nor can I delete it.

There is another Q&A that suggests handling it as part of the AJAX request responsible for inserting the additional DOM:

Binding image lazy loading to new images inserted after ajax request

However, this is how I would do it:

$(document).on('DOMNodeInserted', 'img.lazy', function() {
    $(this).lazyload({
        effect: 'fadeIn'
    });
});

Demo: jsfiddle

like image 31
Cymen Avatar answered Sep 22 '22 20:09

Cymen