Thursday, July 13, 2006

Elegant Image Loading

On my current project I had to display some images associated with a story. We have a servlet that uses ImageMagick and JMagick to dynamically load an image from a database and do various things on the fly like resizing, cropping, etc depending on the params passed in. This servlet is mapped to a variation of the JPG image extension.

When I designed the page and tested it, I noticed that because there might be 12 images going through this process on the page, it appeared that the page loaded very slowly. It also would display those nice little "there's an image getting ready to display here" place holders until the image was finally loaded. This was just annoying and it made for a bad user experience, imho.

To resolve this and make it appear that the images were loading in the background, I put in the following code (click on the image for a larger preview):

What I did here was for each image in the imageList I created a DIV that is not visible when the page loads. Next, I placed the following code in the window.onload event (click on the image for a larger preview):

What this does is creates a new IMG object on the page for each image in the imageList. When an image has completed loading the file given in the SRC attribute, it's onload event is fired. When this happens I use the Scriptaculous Appear function to allow the image to fade in.

When the page loads, you can't see the empy place holder boxes and it appears the page has completed loading. After which you start to see the images fade in, which is a very elegant effect. If the images are cached, they just begin to fade in that much faster.

One other thing I did which I didn't supply the code for was I placed a transparent div over the entire table with a message in the middle saying Images Loading. As soon as the first img.onload event is fired, I Fade that div out. The effect is very nice.

No comments: