Coding with Jesse

Getting an Image's onload to Fire

Are you attaching an onload function to an image but finding it doesn't always get called?

The problem is almost always this: you need to set the onload before you set the src. The reason is obvious when you think about it: if the image is in the cache, the image will be loaded immediately after setting the src, even before the onload is set.

Adding fuel to the fire, Firefox and Safari will let you set an onload immediately after (it seems they don't call the onload until the block of JavaScript finishes). This doesn't happen in Internet Explorer or Opera.

Long story short:

// evil:
var image = new Image();
image.src = 'image.jpg';
image.onload = function() {
    // sometimes called
    alert('image loaded');
};

// good:
var image = new Image();
image.onload = function() {
    // always called
    alert('image loaded');
};
image.src = 'image.jpg';

No matter how many times I come across this bug and find the solution, I end up making the same mistake a few weeks later. I'm hoping that blogging about it will get this stuck in my long-term memory.

Published on September 28th, 2007. © Jesse Skinner

About the author

Jesse Skinner

Hi, I'm Jesse Skinner. I'm a web development coach & consultant. I teach web development teams how to scale up their server infrastructure, improve automated testing and monitoring, reduce costs, and modernize their legacy systems. I focus on empowering teams through customized training and coaching.

Feel free to email me. I'm eager to hear about your challenges and see how I can make your life easier.