You use the imagesLoaded library to check if all the images are loaded before initialising your masonry grid.
Wordpress comes with imagesLoaded, you just need to enqueue it in your theme.
wp_enqueue_script( 'imagesLoaded' );
Then in your javascript you can do an if statement like so:
$('#container').imagesLoaded( function() {
// images have loaded, initialise masonry grid.
});
The Masonry library also has a .layout
method which lays out all item elements. Useful for when an item has changed size.
// jQuery
$grid.masonry('layout')
// vanilla JS
msnry.layout()
https://imagesloaded.desandro.com/
https://masonry.desandro.com/methods.html