'Javascript appendChild onload event

I'm appending the dynamically created image element to document.

var img = new Image();
img.src = 'test.jpg',
img.onload = function() {

    var addedImg = container.appendChild(img);
    console.log(img.width); //old width.
}

The problem here is the fact if I take image dimensions right after container.appendChild(img) it returns the source file dimensions because the appendChild has not finished yet(not repainted?) and dimensions are not re-calculated.

var addedImg = container.appendChild(img);
console.log(img.width) //returns original width of the image

So, I'm wondering if it is possible to catch the load event for appendChild?

I know it is possible using setTimeout/setInterval, but I guess there should be more elegant solution.

var addedImg = container.appendChild(img);
setTimeout(function() {
    console.log(img.width); //return correct resolution after image dimensions were recalculated
}, 1000);

The problem with setTimeout/setInterval is the fact I don't know when element is finally appended and repainted. I have to run it on a loop.

I was trying to listen to DOMNodeInsertedIntoDocument and DOMNodeInserted events however it does not work.

img.addEventListener("DOMNodeInserted", onImageInserted, false);
img.addEventListener("DOMNodeInsertedIntoDocument", onImageInserted, false);

function onImageInserted(event) {
    console.log(img.width); //still wrong width
}

However, it seems to run right after appendChild is fired.

Here is the fiddle so you can see what I'm talking about: http://jsfiddle.net/0zyybmf2/

Note: please don't advise to check the width of the parent container. I need to take a width of the image. Any help with this would be appreciated greatly.



Solution 1:[1]

var img = new Image();
var container = document.getElementsByTagName("div")[0];
container.appendChild(img);

img.onload = function() {
  alert('Width = ' + img.width);
}

img.src = "https://picsum.photos/id/1015/600/400";
div {
    width: 200px;
}

img {
    display: block;
    width: 100%;
    height: 100%;
}
<div></div>

Solution 2:[2]

As 2022 MutationObserver can be a solution.

const callback = ( mutations, mutationObserver ) => {
   mutationObserver.disconnect();
   const MutationRecord = [...mutations];
   console.log( MutationRecord );
};

let mutationObserver = new MutationObserver( callback );

mutationObserver.observe( document.querySelector( "#mmp-map-2b40f571" ), { childList: true, subtree: false } );

document.querySelector( "#mmp-map-2b40f571" ).appendChild( document.createElement( "div" ) );
<div id="mmp-map-2b40f571"></div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 G-Cyrillus
Solution 2