简体   繁体   English

动态创建元素的延迟加载

[英]lazy load for dynamic create elements

On my page in many places I use lazyload effect . 在我的页面上的许多地方,我都使用lazyload效果。
Plugin url http://www.appelsiini.net/projects/lazyload . 插件网址http://www.appelsiini.net/projects/lazyload For images I added class "lazy" and 对于图像,我添加了“ lazy”类,

  <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>

But in other page I dinamic created images with class "lazy" but lazyload don't work ? 但是在其他页面中,我动态创建了具有“ lazy”类的图像,但是lazyload无法正常工作吗? How to fix ? 怎么修 ?

check DEMO 检查演示

HTML HTML

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

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

Just use lazySizes . 只需使用lazySizes即可 This lazyloader is developed with dynamic content in mind. 该lazyloader的开发考虑了动态内容。 No need to trigger an event or to sacrifice separation of concerns by calling methods at different spots in your JS. 无需通过在JS中的不同位置调用方法来触发事件或牺牲关注点分离。

Simply use: 只需使用:

<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>

Here is a demo: http://jsfiddle.net/osnwer4w/3/ 这是一个演示: http : //jsfiddle.net/osnwer4w/3/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM