img onload doesn't work well in IE7

If you don't have to support IE 6, you can just use this CSS.

yourImageSelector {
    max-width: 150px;
    max-height: 150px;
}

IE7 is trying to resize the image before the DOM tree is fully rendered. You need to run it on document.onload... you'll just need to make sure your function can handle being passed a reference to the element that isn't "this."

Alternatively... and I hope this isn't a flameable offense... jQuery makes stuff like this really, really easy.

EDIT in response to EDIT 1:

You can put document.onload(runFunction); in any script tag, anywhere in the body. it will still wait until the document is loaded to run the function.


I've noticed that Firefox and Safari both fire "load" events on new images no matter what, but IE 6&7 only fire "load" if they actually have to get the image from the server -- they don't if the image is already in local cache. I played with two solutions:

1) Give the image a unique http argument every time, that the web server ignores, like

<img src="mypicture.jpg?keepfresh=12345" />

This has the downside that it actually defeats caching, so you're wasting bandwidth. But it might solve the problem without having to screw with your JavaScript.

2) In my app, the images that need load handlers are being inserted dynamically by JavaScript. Instead of just appending the image, then building a handler, I use this code, which is tested good in Safari, FF, and IE6 & 7.

document.body.appendChild(newPicture);
if(newPicture.complete){
    doStuff.apply(newPicture);
}else{
    YAHOO.util.Event.addListener(newPicture, "load", doStuff);
}

I'm using YUI (obviously) but you can attache the handler using whatever works in your framework. The function doStuff expects to run with this attached to the affected IMG element, that's why I call it in the .apply style, your mileage may vary.