Search code examples
jqueryajaxdynamic-data

.load() firing before image ready


I have some dynamically loading images that change depending on the link a user clicks.

I need to get the images width and height before displaying the images so that the page can be formatted correctly, however the .load() event will fire before the image is fully loaded and my width / height calls return NULL or 0.

I need a way to check that the images are actually loaded before trying to get the dimensions.

Any help?

CODE:

Ajax Call

function loadImages() {
    //___ Variables
    var xmlhttp;
    var responseArray = [];

    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function() {

        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            $("#preload").empty();
            //___ Get server response / Convert to Array / Drop last field
            var responseArray = xmlhttp.responseText.split(',');
            responseArray.pop();

            var windowHeight = $(window).height();
            var imgHeight = windowHeight * .9
            if (imgHeight > 1000) {//___ if WindowHeight is > 1000px make images max 900px
                imgHeight = 900;
            }

            //___ Place images in preload
            //$("#preload").append("<div id='contain'></div>");
            for(var i=0;i<responseArray.length;i++){
                $("<img src='"+responseArray[i]+"' id='responseImage"+i+"'>").appendTo("#preload");
            }
            ready();
        }

    };
    //console.log(portLink); //Display link clicked
    xmlhttp.open("GET","includes/displayimagesLive.php?portname="+portLink,true);
    xmlhttp.send();
}

ready() function:

function ready() {
    var div = document.getElementById("preload").childNodes;
    var count = $(div).length;
    console.log(count);

    $("#responseImage0")
        .load(function() {
            //alert("Loaded");
            alert($("#responseImage"+count).width());
        })
        .error(function() {
            alert("Error");
        });
}

Solution

  • Fellow user undefined pointed me to an awesome gitHub plugin called imagesLoaded that is doing the job perfectly.

    Uncanny, really.

    After doing a bunch of research and mucking about on both MAMP and live I went with lazyLoad to get the job done. Mainly because my images are large, but not so huge they need preloading.