9 August 2018

Lazy load background images with jQuery

Background images can be confusing – they don’t have a load event so can’t be lazy loaded in the typical way. To get around this, we need to create an image element, but not in the DOM. We then set the src attribute on this ‘invisible’ image and handle the load event on it. Once it’s loaded, it can then be set as the background image url. Using this approach, the image gets loaded into cache instead of downloaded again. We can remove the data-src attribute at that point and apply a transition.

Firstly set up the element that will have the background image – you’ll need ‘data-src’ on this (containing the image we want to lazy load). It’s also a good idea to use a transparent ‘container’ image as the element source if you want it to retain its dimensions within a responsive design:

We’ll give the image a fade in transition and centre it:

And here’s the JS with comments: