Jquery lazyload with ajax

后端 未结 8 1644
-上瘾入骨i
-上瘾入骨i 2021-01-17 23:26

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

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


        
8条回答
  •  误落风尘
    2021-01-18 00:28

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

提交回复
热议问题