Oliver Nassar

I can be reached at onassar@gmail.com.

For my open source work, check out github.com/onassar


Race Condition When Loading Images Dynamically In JavaScript

View more posts

I've been doing some freelance work on shareasimage.com, much of which revolved around loading images on the client side, dynamically.

This included creating images through canvas, as well as using third party APIs to allow users to select images from their social networks (using Ink File Picker). Every now and then, when I allowed my browser to cache assets, weird things would happen with the onload event for Image objects.

Here's a sample flow I was running:

var image = (new Image());
image.src = 'http://full-path-to-image/';
image.onload = function() {
    // Code
};

When I had cache disabled, things would (normally) work beautifully. But when I had cache working normally, it would sometimes fail to work properly. Can you see the bug?

Here's the fixed code:

var image = (new Image());
image.onload = function() {
    // Code
};
image.src = 'http://full-path-to-image/';

The issue seemed to be that I was specifying the image data (either src or raw image bit data) before the onload was bound to the object. When the object wasn't in cache, this wasn't a problem, because the onload line would be assigned to the image before the image had loaded. But when the object was in cache, that line would execute immediately, and the browser/stack wouldn't have found an onload event to call.

Long story short, ensure you always specify the onload event before specifying the image data itself :)