Elegant <img> presentation
Sep 17 2011 · Web Design
While it’s easy to decry Flash and espouse the merits of HTML5, it’s worth taking a look at some of the positive elements found on many Flash sites and seeing what can be brought over to the HTML side. One very obvious aspect is the presentation of images. Flash sites almost never render an image in the way that an <img> tag is rendered by the browser. Flash sites will (typically) elegantly animate or fade an image in/out whereas the default browser behavior for HTML is to progressively render the image as it is received (sometimes images are 2D interlaced for a slightly better effect). Even worse, many HTML sites leave width and height as attributes to be determined dynamically for the <img> tag, resulting in page content shifting around as images are loaded.
So, I did a little experiment with 2 goals in mind:
- Elegant presentation of images with HTML + JS
- Very simple markup, one iota above what’s necessary for a typical <img> tag
I’m pretty happy with the results.
View the demo
(disable your browser cache so that loading latency is accurately taken into account)
Here’s what I did:
1. Make the <img> elements.
Things to note:
- The data-src attribute is an HTML 5 custom data attribute. It specifies the URL of the image to be loaded.
- The src attribute uses the data URI scheme to load and set the initial image displayed in the img element. Leaving the src attribute blank is not desirable as it will collapse the img element and only show the alt tag (the same behavior occurs initially if a URL to an image is specified). Specifying a data URI allows the image to be loaded as part of the document itself. The data URI shown above is for a 1×1, transparent PNG. A GIF preloader would probably be a good idea here.
- The width and height attributes are specified. This is not strictly necessary, but in keeping with the theme of elegance, this prevent other content on the page from shifting after images are loaded.
window.onload = function ()
var imgElem = $(this);
var src = imgElem.attr('data-src');
var img = new Image();
img.src = src;
img.onload = function ()
imgElem.fadeTo('fast', 0.0001, function ()
For simplicity, jQuery is used.
- The <img> element is faded out (actually faded to an alpha of 0.0001 because a total fadeOut to 0 will effectively remove the element from the document rendering).
- The src attribute is changed to the the URL of the loaded image.
- The <img> element is faded in.
The important bit is changing the src attribute; the effect itself, whether it’s fading, sliding, etc. is not terribly important.