Steve Taylor photo

Delay image loading with jQuery

Inspired by this post, I’ve recently incorporated into my starter theme a method to defer the loading of certain images. This can drastically improve page loading speed for mobile devices on slow connections. The device won’t have to wait until all the images are loaded before rendering the page.

First, a bit of jQuery to be run once the document has finished loading:

jQuery( document ).ready( function( $ ) {
	var di = $( 'img[data-defer-src]' );
	if ( di.length ) {
		di.each( function() {
			$( this ).attr( 'src', $( this ).data( 'defer-src' ) );
		});
	}
});

This finds img tags with a data-defer-src attribute. Then it runs through each of them and replaces the proper src attribute’s value with the data-defer-src value.

Naturally this implies the following kind of markup for any images you want deferred loading applied to:

<img src="placeholder.gif" data-defer-src="actual-image.jpg" alt="My image" width="100" height="250">

They don’t have to be large images. Usually we’re looking at images that can’t be included in a sprite. Illustrations and photos are a good example. I came across this technique looking into loading Gravatars in a long series of comments. In this case there would be many different HTTP requests to an external server—not good for page load speeds, and an ideal candidate for deferred loading.

And yes, you read that right—placeholder.gif. Yes, it’s a transparent single pixel! Old school or what? There are other placeholder techniques around, but this is simple and effective. Whatever your technique, you need a placeholder to, well, hold the layout in place until the actual image loads, to prevent lots of jigging about.