Bombel
Bombel

Reputation: 159

Image object onload function firing instantly

I'm creating a few Image objects and when I setup network throttling in Dev Tools I see that onload functions are invoking before my images are fully loaded.

I really cannot find the solution. My code:

    function imgObjects(data) {
    for (var i in data) {
        img[data[i].id] = new Image();
        img[data[i].id].onload = imgReady();
        img[data[i].id].name = data[i].name;
        img[data[i].id].src = data[i].image;
    }
}

function imgReady() {
    imgReadyCount++;
    console.log('Count: ', imgReadyCount);
}

I you happen to know the answer please provide it in vanilla js, thanks!

Upvotes: 2

Views: 1118

Answers (3)

Bekim Bacaj
Bekim Bacaj

Reputation: 5955

"Image object onload function firing instantly"

That's because you are preloading them. The onload event fires as soon as the image source as finished loading regardless of the fact that they are still orphaned i.e.: not appended to the document tree. And of course the term "instantly" applies to the fact that they are already cashed; and therefore are being pulled from the cash - "instantly".

p.s.: You need to reserve yourself from specifying the img.src until you think you are ready to handle the onload event.

Upvotes: 0

Josh
Josh

Reputation: 1474

Add an event to the document;

document.addEventListener("DOMContentLoaded", function(event) { 
    //your code to run since DOM is loaded and ready
});

Upvotes: 0

Travis J
Travis J

Reputation: 82297

The problem is your event handler assignment.

img[data[i].id].onload = imgReady();//you call the function here

Instead it should be

img[data[i].id].onload = imgReady; //note that the handle is stored

Which will avoid calling the handler immediately and will also then not result in undefined being assigned to the onload handler.

Upvotes: 4

Related Questions