Elements shift on page using Bootstrap and Masonry

Viewed 84

I'm making a website using Bootstrap and Masonry. All works fine, but when the page loads, for the first 2 seconds the elements shift from left to center.

How could I make the page load instantly with the grid elements perfectly in the center. The shifting of elements looks ugly.

The code: http://bl.ocks.org/bollwyvl/e77b3c9d3b322e511ecf

Website: http://bl.ocks.org/bollwyvl/raw/e77b3c9d3b322e511ecf/

I'm using the above code. (Please refresh the website to see the effect).

It has to do something with the following code executing only after the jQuery assets have loaded. Is there a workaround to make the grid elements display perfectly in center when the website loads.

jQuery(window).bind('resize', function () {
    if (!jQuery('#posts').parent().hasClass('container')) {
        // Resets all widths to 'auto' to sterilize calculations

        post_width = jQuery('#post').width() + gutter;
        jQuery('#posts, body > #grid').css('width', 'auto');
        // Calculates how many .post elements will actually fit per row. Could this code be cleaner?

        posts_per_row = jQuery('#posts').innerWidth() / post_width;
        floor_posts_width = (Math.floor(posts_per_row) * post_width) - gutter;
        ceil_posts_width = (Math.ceil(posts_per_row) * post_width) - gutter;
        posts_width = (ceil_posts_width > jQuery('#posts').innerWidth()) ? floor_posts_width : ceil_posts_width;
        if (posts_width == jQuery('#post').width()) {
            posts_width = '100%';
        }
        // Ensures that all top-level elements have equal width and stay centered

        jQuery('#posts, #grid').css('width', posts_width);
        jQuery('#grid').css({'margin': '0 auto'});
    }
}).trigger('resize');
1 Answers
Related