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.
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.
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.
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.).
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With