Using masonry with imagesloaded

给你一囗甜甜゛ 提交于 2019-11-27 14:08:34

imagesLoaded is not included in Masonry, so you should use separate plugin. I would recommend to use compiled .min version.

Regarding your problem with stacked images: the problem is not in imagesLoaded neither Masonry. In your code imagesLoaded is waiting until all images loaded and then fires masonry. Having all images loaded, Masonry plugin can properly define their sizes and put on grid. Before that, browser loads images as usually and display 'em according to defined CSS, that's why they're messed up.

One of the possible solution is to hide elements by default and then fadein while imagesLoaded confirm, that images loaded:

$(document).ready(function() {

  var $boxes = $('.box');
  $boxes.hide();

  var $container = $('#post-area');
  $container.imagesLoaded( function() {
    $boxes.fadeIn();

    $container.masonry({
        itemSelector : '.box',
        columnwidth: 300,
        gutter: 20,
        isFitWidth: true,
        isAnimated: !Modernizr.csstransitions
    });    
  });
});

Another solution is to initialize Masonry inside $(window).load() instead of $(document).ready(). This will trigger Masonry after all the media on the page has loaded – images, fonts, external scripts and stylesheets, etc.

$(window).load(function(){
    $('#container').masonry({
        // options...
    });
});

Install

npm install masonry-layout --save

npm install imagesloaded --save

Then vanilla js options would be

'use strict'

const Masonry = require('masonry-layout')
const imgloaded = require('imagesloaded')
const elem = document.querySelector('.grid')
var imgLoad = imgloaded( elem )
    function onAlways() {
        const msnry = new Masonry( elem, {
            // options
            columnWidth: '.grid-sizer',
            // do not use .grid-sizer in layout
            itemSelector: '.grid-item',
            percentPosition: true,
            gutter: 10
        })
    // console.log('all images are loaded')
}
if (elem) {
    // bind with .on()
    imgLoad.on( 'always', onAlways )
    // unbind with .off()
    // imgLoad.off( 'always', onAlways )
}

Then check the console for all images are loaded.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!