javascriptmasonryimagesloaded

Imagesloaded not working with Infinite Ajax Scroll and Masonry


I have a website the uses bootstrap and the news that I have created with masonry, I used the Infinite Ajax Scroll, that call other news in a different div instead the pre-default. Very often, however, if one scrolls the page quickly, or if you have a slow connection, the elements overlap and do not return to their place, and I think this is due to the fact that it can't load images. I tried to integrate Imagesloaded but it seems not work properly... and I don't know what to do... Here is the source as I have proceeded, HTML:

<div class="row masonry_base altre">
  {$news}
</div>

<div class="row masonry altre">
  <div class="col-lg-4 col-md-6 col-xs-12 post-grid">
    {$news_scroll}
  </div>
</div>

JS:

<script>
(function($) {
"use strict";

  var $container = $('.masonry_base');
  $($container).imagesLoaded( function(){
    $($container).masonry({
      itemSelector: '.post-grid',
      columnWidth: '.post-grid'
    });
  });
})(jQuery);
</script>

<script type="text/javascript">
  var container = document.querySelector('.masonry');
  var msnry = new Masonry( container, {
    itemSelector: '.post-grid',
        gutterWidth: 20
  });
msnry.reloadItems()
    var $container = $('.masonry');
    $($container).imagesLoaded( function(){
        $($container).masonry({
            itemSelector: '.post-grid',
            columnWidth: '.grid',
            gutterWidth: 20
        });
    });


  var ias = $.ias({
    container: ".masonry",
    item: ".post-grid",
    pagination: "#pagination",
    next: ".next a",
    delay: 1200
  });

  ias.on('render', function(items) {
    $(items).css({ opacity: 0 });
  });

  ias.on('rendered', function(items) {
    msnry.appended(items);
  });

  ias.extension(new IASSpinnerExtension());
  ias.extension(new IASNoneLeftExtension({
        html: '<div class="btn btn-info btn-block btn-icon-left ias-noneleft" style="text-align:center"><p><em>No news</em></p></div>'
    }));
</script>

Solution

  • This code :

    $($container).imagesLoaded( function(){
        $($container).masonry({
            itemSelector: '.post-grid',
            columnWidth: '.grid',
            gutterWidth: 20
        });
    });
    

    Only applies imagesLoaded to whatever $container happens to be at its execution. It doesn't apply to dynamically added content. You should call this function again to the dynamic content added. Perhaps in your rendered callback.

    Also, you should just call msnry.layout() to adjust content after the images had been loaded (It's not necessary to call $.masonry again)

    Hope it helps