Wednesday, July 03, 2013

Generated Image URLs and Broken Links

I had a task at a job that I recently held which was to render a list of images into a table with some metadata attached to them. However, there was a small catch. These image URLs that were being provided were generated and the image was not guaranteed to be at the URL that was created. So I had to find a way to render an image unavailable place holder or render the image. Here is the solution I came up with.
Let us start out with what the data looks like:

I already had a not found placeholder so I decided that every image would have that as it's source image. This would mean that I would be seeing an image for every entry in this list.

Now came the part that required me to work some magic. But first I needed to provide the actual image source to the image tag.

With both the image placeholder and the assumed working image I set to work with a single event that would fire off after the page was loaded.

What this does is pretty simple. For each of the images that we are rendering into our table we attempt to load the image URL that is stored in the data-src attribute. If 'the one event' is successful then we replace the URL in the image source attribute for the value in the data-src attribute. So where is the magic? It is inside the one event, the handler is only called when the image loads. I use jQuery to construct an image tag with a source value which will request the image. If the image does not return successfully, the load event never fires and the thumbnail persists.

This was a fun little solution and it may need to have some performance enhancements for when displaying large numbers if images, however, the solution was designed around a very limited presentation.

No comments:

Ajax Lesson

NOTE : This lesson uses jQuery as the interface for basic AJAX work. By no means is AJAX a product of jQuery and you do not need jQuery to ...