Mark Southard

Deferred Images for Faster Load times

According to research by Akamai, a 100-millisecond delay in website load time can reduce conversion rates by seven percent; a two-second delay can increase bounce rates by over 100 percent; and more than half of mobile visitors will leave a page if it takes more than three seconds to load. Furthermore, Google has started factoring both mobile and desktop page speeds into search rankings. Clearly in today’s web, a performant website is critical to keep visitors on your site and to rank high in search results.

A simple, quick win that I’ve found for improving page speed centers around how you load your images. For most web pages, I will load images above the fold regularly, and defer the loading of images beyond the fold. By deferring the loading of images further down in the content, we can improve the perceived performance of the page.

For images beyond the fold, I’ll add them as follows:

<img
  src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="
  data-src="https://example.com/images/race-car.jpg"
  alt="Super fast race car"
/>

The src for the image is a single transparent pixel that has been base64 encoded to prevent additional server requests. The real URL for the image is added as the data-src attribute. Once the page has loaded, I use a small bit of JavaScript to swap out real image for the placeholder image:

function loadImages() {
  var imgDefer = document.querySelectorAll('[data-src]')
  for (var i = 0; i < imgDefer.length; i++) {
    imgDefer[i].setAttribute('src', imgDefer[i].getAttribute('data-src'))
  }
}
window.onload = loadImages

As you can see, I grab all of the images that have a data-src attribute and then loop over them, setting the real image URL as the src attribute. This simple bit of code can greatly reduce the perceived amount of time that the page takes to load. By reducing the load time, you should see a reduction in bounce rates and an uptick in conversions.

This technique, however, assumes that you are loading a fairly small page that does not have hundreds of images. If you do have a page that has hundreds of images, you should use a different technique to lazy load your images (load them only when they are close to being within the viewport). Your mobile users will appreciate you respecting their mobile data plan limitations.

What’s your favorite, simple tip for improving page speed performance?

Send me a message on Twitter @marksouthard

Never miss a post again

Get each new blog post delivered directly to your inbox.