Image object onload function firing instantly

折月煮酒 提交于 2021-02-04 21:16:48

问题


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!


回答1:


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.




回答2:


Add an event to the document;

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



回答3:


"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.



来源:https://stackoverflow.com/questions/37126849/image-object-onload-function-firing-instantly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!