Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to set onload function before setting src for an image object?

I was told it is necessary to set the onload function before setting src for an image object. I've searched in SO for this.

I found this code:

var img = new Image();
img.src = 'image.jpg';
img.onload = function () {
    document.body.appendChild(img);
};

But most people believe that onload should be written before src like this:

var img = new Image();
img.onload = function () {
    document.body.appendChild(img);
};
img.src = 'image.jpg';

MUST it be written in this order? Are there any cases when the above code will cause an error (like if an image is too big)?

If you anyone can show me some examples, I will be very appreciate.

like image 718
pktangyue Avatar asked Feb 01 '13 14:02

pktangyue


People also ask

Is onload necessary?

Yes, there could be unexpected consequences. But, no, it's not absolutely necessary. The timing could be off for things still loading, like complicated layouts, deep DOM structures, dynamic HTML from other scripts, or images. To avoid these situations, it's always safest to wrap your script in an onload event.

What does IMG onload do?

Description. The onload property of an Image object specifies an event handler function that is invoked when an image loads successfully. The initial value of this property is a function that contains the JavaScript statements specified by the onload attribute of the <img> tag that defined the Image object.

Why do we need window onload?

Definition and Usage. The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).

Does Div have onload?

The onload event can only be used on the document(body) itself, frames, images, and scripts. In other words, it can be attached to only body and/or each external resource. The div is not an external resource and it's loaded as part of the body, so the onload event doesn't apply there.


1 Answers

It doesn't have to, but if setting the src and the image loads before your handler is attached, it won't fire.

JavaScript operates asynchronously. Setting the src will cause the web browser to load the image outside the main execution flow. If onload isn't set at the time that operation completes - which could be between setting src and onload.

like image 170
Daniel A. White Avatar answered Oct 21 '22 19:10

Daniel A. White