Search code examples
jqueryjquery-pluginswaitforimages

Combining Masonry with Waitforimages, image loading


I noticed while testing Masonry that if I shift-reload in Firefox (to hard reload), then the layout would be off by the height of any image in the page. I think the div heights must depend on knowing the image height, which makes sense.

Since I'm already using jquery.waitforimages.js, I added this at the end of my page and my script:

$wall.waitForImages(function() {

    $wall.masonry( 'reload' );

});

Although everything works, now I have an error that I see in Firebug, which only occurs if I don't hard-reload. So I'm assuming this error happens when the image is already cached: "cannot call methods on masonry prior to initialization; attempted to call method 'reload'".

Is there a way out of this? Thanks!


Solution

  • Answer: Use the script called imagesLoaded with Masonry, since the same author wrote both & they work together.
    Script: https://github.com/desandro/imagesloaded/

    In your jQuery, something like:

        $wall = $('#mydiv');
        $wall.imagesLoaded(function(){
                // call your layout function, something like:
                // layoutBricks();
        });
    

    This should help avoid the Heisenbug. I have not tested this new image loading script on my other gadgets, so I don't know about that yet.