Receiving Callback from an Image

When writing a Web 2.0 app, function completes get to be pretty important. In fact, they’re the little signal that a function can send out to the larger program that says, “Hey, I’m done, now do something else”; callback like this is a pretty important thing.

Take the case of a web application that loads a list of items from an external source. Generally, most AJAX libraries, and even XHTTP request code that you roll on your own, gives you the opportunity to write a function that runs onsuccess. That’s great: when your code is done executing, bam!, your function runs. In most cases, that’s great. However, consider the case of a set of images loaded externally then inserted into the page dynamically: the images might be received from the server and stuck into the page, but they might not be fully rendered, depending on the environment.

I ran across this interesting little quirk while working on a Web 2.0 app using Flickr. I loaded a bunch of images from Flickr, dynamically built them and inserted them into my page, and, voila, they’d slowly render, dial-up modem style. Not optimal. I almost gave up until a quick Google showed me that, in face, Images Can “Call back,” too!

Thanks to evolt, I was able to come up with this little design pattern:

  • In a for loop, iterate through an array of images to be added.
  • For each iteration, dynamically build an image, using document.createElement(’img’), or your image object.
  • At the end of each iteration, test to see if the current image is the last image in your array. If it is, assign your “all loaded” function to that image’s onload event handler. Otherwise, assign an arbitrary little callback function if you’d like.

Now, your function can learn when all images are loaded. Also, if you’d like more flexibility or interactivity, you can map each individual image’s event handler to a different function (say, update a progress bar with what image is being loaded, or show a progress percentage). All thanks to the image itself.

Comments are closed.

I'm Reading…
Search This Site

AddThis Feed Button

Need great hosting?

Categories