Jquery 延迟加载与 ajax

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13791740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:57:37  来源:igfitidea点击:

Jquery lazyload with ajax

jqueryajaxlazy-loading

提问by tebdilikiyafet

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

我在我的电子商务网站上使用了 lazyload()。lazyload() 效果很好。我使用此代码来做到这一点:

$(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().

还有一些过滤器,如颜色、价格等,运行 ajax 并显示新结果。当新结果出现时,lazyload() 不起作用。我知道我必须将lazyload() 与live()、delegate() 或on() 一起使用。但我是 jquery 的新手,我做不到。有人可以帮我吗?我的 jquery 版本是 1.7.2,我们可以使用 on()。

采纳答案by Cymen

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:

还有另一个问答建议将其作为负责插入额外 DOM 的 AJAX 请求的一部分进行处理:

Binding image lazy loading to new images inserted after ajax request

将图像延迟加载绑定到 ajax 请求后插入的新图像

However, this is how I would do it:

但是,这就是我将如何做到的:

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

Demo: jsfiddle

演示:jsfiddle

回答by AbdelHady

Shortly, the best optimized wayto do this is to call the lazyload in your ajax's successfunction:

很快,最好的优化方法在 ajax 的成功函数中调用延迟加载

$.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 callto the lazyload plugin, you have 2 options:

但是如果你想集中你对lazyload插件的调用,你有两个选择

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,

但请注意这里的“#container”,它是容器的选择器,您将在其中显示新加载的内容,因此上面的代码将在此容器内侦听任何新添加的内容,以便在新图像上再次运行延迟加载,

Second:(recommended)

第二:(推荐)

Calling your custom lazyload by adding it to your JQuery:

通过将其添加到您的 JQuery 来调用您的自定义延迟加载:

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

then, call it in all your AJAX requests:

然后,在所有 AJAX 请求中调用它:

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

回答by RafaSashi

In addition to AbdelHady's answer you can lazy load new images on success as a callback or use when()this way:

除了 AbdelHady 的回答之外,您还可以在成功时延迟加载新图像作为回调或使用when()这种方式:

   $.when(load_new_image()).done(function(i){

            if($('img.lazy').length){

                 $('img.lazy').lazyload({ 

                          effect:'fadeIn'

                 }).removeClass('lazy').addClass('lazyloaded');

            }

        });

        function load_new_image() {

            return $.ajax({
                url: "your url here",
                type: "Post",
                success: function(response){

                     //append new content
                    $('#container').append(response);

                }
            });
        }

NOTA BENE

诺塔贝尼

回答by Mark

Lazyload for images loaded after window load (e.g. AJAX) will not display any images before a scroll event. This is because it is internally hardcoded to trigger the initial update after the window load event. All the above answers, for now, are wrong.

在窗口加载(例如 AJAX)之后加载的图像的延迟加载不会在滚动事件之前显示任何图像。这是因为它在内部硬编码以在窗口加载事件之后触发初始更新。目前,以上所有答案都是错误的。

回答by antoniputra

I have same problem, when using waypoints infinite scroll with lazy load image. (but not work on ajax content).

我有同样的问题,当使用带有延迟加载图像的航点无限滚动时。(但不适用于 ajax 内容)。

and I fixed that issue with this :

我用这个解决了这个问题:

$("img.lazy").lazyload({
    effect : "fadeIn",
    event: "scrollstop",
    skip_invisible : true
}).removeClass('lazy');

$(document).bind('DOMNodeInserted', function(e) {
    $("img.lazy").lazyload({
        effect : "fadeIn",
        event: "scrollstop",
        skip_invisible : true
    }).removeClass('lazy');
});

I bind the lazy load configuration on DOMNodeInsertedevent.

我在DOMNodeInserted事件上绑定了延迟加载配置。

回答by Dipen

For my scenario when the page is loaded I will get list of template with template Id. Based on that template Id I use jQuery Lazyto load base64 encoded images using ajax and load image lazily on my page.

对于加载页面时的场景,我将获得带有模板 ID 的模板列表。基于该模板 Id,我使用jQuery Lazy使用 ajax 加载 base64 编码的图像,并在我的页面上延迟加载图像。

Hope you will get some idea of my approach

希望你能对我的方法有所了解

$(document).ready(function() {
  let imageArray = [0, 1, 10, 100, 1000, 1001];

  let parsedImageArray = $.map(imageArray, function(value) {
    return "<div class='lazy' data-loader='ajaxLoader' data-src='/echo/html/' data-method='post' contentId='" + value + "'></div><br>";
  });

  $("#content").html(parsedImageArray);

  console.log("Here" + parsedImageArray)
});


$(document).bind('DOMNodeInserted', function(e) {
  $('.lazy').lazy({
    effect: "fadeIn",
    event: "scrollstop",
    skip_invisible: true,
    removeAttribute: false,
    ajaxLoader: function(element, response) {
      let thumbnailId = element.attr("contentId");
      console.log("Here" + thumbnaiId);
      $.get("https://picsum.photos/id/" + thumbnailId, function(srcValue, status) {
        //for me i have to pull the base64 encode image from my server 
        let defaultImageDom = generateThumbnailImage(tempSrc);
        element.html(defaultImageDom);
        element.removeClass('lazy');
      }).fail(function(jqXHR, textStatus, errorThrown) {
        let defaultImageDom = generateThumbnailImage("");
        element.html(defaultImageDom);
        element.append("<em>Error Getting Thumbnail Preview</em>");
        element.removeClass('lazy');
      });
    },
  });
});

function generateThumbnailImage(srcValue) {
  let defaultImageDom = new Image();
  defaultImageDom.height = 200;
  defaultImageDom.style.borderColor = "#d5d5d5";
  defaultImageDom.style.borderWidth = "1px";
  defaultImageDom.style.borderStyle = "solid";

  if (srcValue && srcValue.length > 0) {
    defaultImageDom.src = srcValue;
  } else {
    //set your fallback image link
    defaultImageDom.src = "data:image/gif;base64,R0lGODdhAQABAPAAAMPDwwAAACwAAAAAAQABAAACAkQBADs=";
  }
  return defaultImageDom;
}
.lazy {
  width: 700px;
  height: 467px;
  display: block;
  /* optional way, set loading as background */
  background-image: 'data:image/gif;base64,R0lGODdhAQABAPAAAMPDwwAAACwAAAAAAQABAAACAkQBADs=';
  background-repeat: no-repeat;
  background-position: 50% 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.lazy/1.7.9/jquery.lazy.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.lazy/1.7.9/jquery.lazy.plugins.min.js"></script>

<div id="content">
</div>

回答by tebdilikiyafet

I use the code below and it worked:

我使用下面的代码并且它有效:

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

回答by alexzg

   $(document).ajaxStop(function() {$('.loading').removeClass('in');
    $("img.lazy").lazyload({
                effect: "fadeIn",
               container: $("#scrollable"),
               threshold: 100,
            })

      });

works for ajax images. but however, not showing the first image by default. the update is not triggered.

适用于 ajax 图像。但是,默认情况下不显示第一张图像。不触发更新。