【问题标题】:lazy load for dynamic create elements动态创建元素的延迟加载
【发布时间】:2019-08-17 00:58:10
【问题描述】:

在我的页面上很多地方我都使用了延迟加载效果。
插件网址http://www.appelsiini.net/projects/lazyload。 对于图像,我添加了“懒惰”类和

  <input type="button" onclick="fn()" >
<script type="text/javascript">

  $(function() {
    fn()
     $("img.lazy").lazyload();
  });

function fn(){


   var img = document.createElement('img');
   img.setAttribute('data-original','bg.jpg')
   img.className='lazy'
   document.body.appendChild(img);
}

</script>

但在其他页面中,我用“lazy”类动态创建了图像,但lazyload 不起作用?如何解决?

【问题讨论】:

  • 创建新图像后,对其应用延迟加载插件。
  • 你如何创建动态图像?请添加代码

标签: javascript jquery


【解决方案1】:

只需使用lazySizes。这个惰性加载器是在考虑动态内容的情况下开发的。无需通过在 JS 的不同位置调用方法来触发事件或牺牲关注点分离。

简单使用:

<input type="button" onclick="fn()" value="add image">
<img data-src="http://lorempixel.com/400/200/" class="lazyload" />
<script>
    function fn() {
        var img = document.createElement('img');
        img.setAttribute('data-src', 'http://lorempixel.com/400/200/')
        img.className = 'lazyload';
        document.body.appendChild(img);
    }

    fn();
</script>

这是一个演示:http://jsfiddle.net/osnwer4w/3/

【讨论】:

    【解决方案2】:

    检查DEMO

    HTML

    <input type="button" onclick="fn()" value="load Image" >
    

    JQUERY

    function fn(){
      $('<img>')
        .data('original','https://www.google.co.in/logos/doodles/2015/126th-anniversary-of-the-public-opening-of-the-eiffel-tower-4812727050567680-hp.jpg')
        .addClass('lazy')
        .appendTo('body')
      ;
      setTimeout(function(){
           $("img.lazy").lazyload(); 
      },100);      
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2021-05-30
      相关资源
      最近更新 更多