问题
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