Gracefully loading images

User experience is important, and it’s the little things that matter the most. Make their visit seamless and they’ll come back time and time again. One of many ways you can achieve this is by loading images “nicely”, not by thrusting them in their face but by displaying a default image and then gracefully loading the image.

<div class="wrapper">
    <img src="..." alt="...">

This is all the HTML that you’ll need. A few people are probably asking “won’t the default image be loaded after the actual image?” Potentially, yes. But there are ways around this. You can use base64 encoded URL’s which contain the PNG image which will not require any extra HTTP requests. There are several ways in which you can add this:

  1. In the external stylesheet.
  2. In the critical CSS (“inline CSS“).
  3. In the wrapper class itself.

The best method will be dependant on your indivdual circumstances, but 1 and 2 would be my recommendations. You’ll want to use the CSS below, replacing the ABC123 with the base64’d version of your image – there are many, many websites that offer this for free (click here for a Google search).

.wrapper{background:url(data:image/png;base64,ABC123) no-repeat top left}
.wrapper img{opacity:0}

You’ll also note that we hide the real image. This is so we can see the background image below and also so that it will not just “pop” in when it loads. So, now we need the Javascript to listen for the image load and then fade it in, and we have a lovely graceful image load.

// Make the image fade in gracefully
$(".wrapper img").on("load", function() {
	$(this).animate({ opacity: 1 }, 500);
}).each(function() {
	// Images can sometimes be loaded from cache. In this case we need to
	// tell the image it has loaded, otherwise it might not fade in.
	if (this.complete) {
		$(this).trigger({ type: "load" });