I\'m appending the dynamically created image element to document.
var img = new Image();
img.src = \'test.jpg\',
img.onload = function() {
var addedImg = co
var img = new Image();
var container = document.getElementsByTagName("div")[0];
container.appendChild(img);
img.onload = function() {
alert('Width = ' + img.width);
}
img.src = "http://globe-views.com/dcim/dreams/image/image-03.jpg";
div {
width: 200px;
}
img {
display: block;
width: 100%;
height: 100%;
}
<div></div>
Unfortunately, it seems that you have to hand the controls back to the browser (using setTimeout()
as you did) before the final dimensions can be observed; luckily, the timeout can be very short.
container.appendChild(img);
setTimeout(function() {
console.log(img.width);
}, 0);
In other words, the repaint (and layout update) is done as soon as your function returns and before the setTimeout
fires.
Btw, it's advisable to only set the .src
property after you've attached the load handler; I've had to debug my code a few times before I realised that cached images may trigger the load handler immediately upon changing .src
.
Demo