Как правильно установить высоту div при загрузке изображения

Я пытаюсь создать веб-сайт сетки, но при загрузке он отображается как первое изображение. Поэтому я использую функцию getImageSize из этого Получить высоту изображения до его полной загрузки, чтобы установить высоту imageDiv, но все равно не удалось. Скажите, почему и как это исправить? Спасибо.

первое изображение введите здесь описание изображения второе изображение введите здесь описание изображения

    $(document).ready(function(){
        var $container = $('#container'); 
        ajaxGetJson(3,1,$container);  //get data from json
        window.onscroll = function(){
            if(scrollside()){  //if scroll 
                ajaxGetJson(3,2,$container); //get data from json again
            }  
        };
});

function ajaxGetJson(actId,page,container){
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "/api/posts",
        data:{actid:actId,page:page},
        success:function(json_data){
            var items = []
            $.each(json_data,function(index,value){
                var box = document.createElement('div');
                box.className = "box";
                var $box = $(box).appendTo(container);
                var content = $("<div>").addClass("content").appendTo(box);
                var imgDiv = $("<div>").addClass("imgDiv").appendTo(content);
                var $img = $("<img>").attr("src",$(value).attr("post_thumb_url")).appendTo(imgDiv);
            getImageSize($img, function(width, height){
                imgDiv.css("height",height);//console correct height in the first 15 items.
            });
                items.push(box);
                });
            jqueryMasonry(page,items);
            }
        });
}

//using masonry 
function jqueryMasonry(page,items){
    if(page==1){
        var $container = $('#container');
        $container.imagesLoaded(function(){
            $container.masonry({
            itemSelector : '.box'
            });
        });
    }
    else{
        var $container = $('#container');
        var $boxes = $(items);
        $container.masonryImagesReveal($boxes);        
    }
}
// this function is tell user scroll enough height
function scrollside(){
    var box = $(".box");
    var lastboxHeight = box.last().get(0).offsetTop+Math.floor(box.last().height()/2);
    var documentHeight = $(document).width();
    var scrollHeight = $(window).scrollTop();
    return (lastboxHeight<scrollHeight+documentHeight)?true:false;
}
//this function is for images show properly,I found it here https://github.com/desandro/masonry/issues/534
$.fn.masonryImagesReveal = function( $items ) {
  var msnry = this.data('masonry');
  var itemSelector = msnry.options.itemSelector;
  // hide by default
  $items.hide();
  // append to container
  this.append( $items );
  $items.imagesLoaded().progress( function( imgLoad, image ) {
    // get item
    // image is imagesLoaded class, not <img>, <img> is image.img
    var $item = $( image.img ).parents( itemSelector );
    // un-hide item
    $item.show();
    // masonry does its thing
    msnry.appended( $item );
  });
  return this;
};

//I found a solution here https://stackoverflow.com/questions/23390393/get-image-height-before-its-fully-loaded
function getImageSize(img, callback){
    img = $(img);

    var wait = setInterval(function(){        
        var w = img.width(),
            h = img.height();

        if(w && h){
            done(w, h);
        }
    }, 0);

    var onLoad;
    img.on('load', onLoad = function(){
        done(img.width(), img.height());
    });


    var isDone = false;
    function done(){
        if(isDone){
            return;
        }
        isDone = true;

        clearInterval(wait);
        img.off('load', onLoad);

        callback.apply(this, arguments);
    }
}

person Windsooon    schedule 06.08.2015    source источник