First, if you're getting the image from the document, you don't need to call new Image
.
You do need to wait until the img
element exists, and until the img
loads.
That's easiest if you add the image with the script, and hook the load
event before setting src
:
<body>
<div id="ad">
<div id="banner"></div>
</div>
<script>
var img = document.createElement('img')
img.className = "top";
img.id = "top";
img.onload = function() {
alert(this.width + 'x' + this.height);
};
img.src="frame_2.jpg";
document.getElementById("banner").appendChild(img);
</script>
</body>
You can do it with the image in the HTML, though, you just have to allow for the possibility the image may have already loaded before you hooked the event:
<body>
<div id="ad">
<div id="banner">
<img class="top" id="top" src="frame_2.jpg"/>
</div>
</div>
<script>
var img = document.getElementById("top");
img.onload = loaded;
if (img.complete) {
loaded();
}
function loaded() {
if (img) {
alert(img.width + 'x' + img.height);
img.onload = null;
img = null; // Just as a marker in case of repeated calls
}
};
</script>
</body>