Lazy Loading Responsive Images in WordPress Without a Plugin

If content is king, then performance is a close second.

Lazy loading is a technique used to defer the downloading of resources by the browser before they are needed. As a user scrolls down the page, images will come into view as they enter the window. Not only will lazy loading images improve the performance of your site, it also helps to create a smoother experience for your users.

The Javascript

In this example, we’ll be using lazysizes to handle the javascript. Check out the Github repo for detailed installation and usage instructions.

The PHP

Assuming you have lazysizes installed, let’s get to the code we need to start lazy loading our images in WordPress.

The wp_get_attachment_image function is how we create an HTML img element representing an image attachment in WordPress. It provides us with a number of properties that allow us to modify the output we need to start lazy loading our images.

// getting the featured image id as an example
$attachment_id = get_post_thumbnail_id( $post->ID );
$size = 'large';
echo wp_get_attachment_image( $attachment_id, $size, false, [
    'class' => 'lazyload',
    'src' => '#',
    'srcset' => '#',
    'data-src' => wp_get_attachment_image_url( $attachment_id, $size ),
    'data-srcset' => wp_get_attachment_image_srcset( $attachment_id, $size )
]);

Now you could just place the code above in your templates and call it a day, but we can do better. Let’s wrap our code in a neat little function that we can call instead.

function lazy_attachment($attachment_id, $size)
{
    echo wp_get_attachment_image( $attachment_id, $size, false, [
        'class' => 'lazyload',
        'src' => '#',
        'srcset' => '#',
        'data-src' => wp_get_attachment_image_url( $attachment_id, $size ),
        'data-srcset' => wp_get_attachment_image_srcset( $attachment_id, $size )
    ]);
}

Place the code above in your functions.php file and you can now call your lazy loading images with a single line of code.

lazy_attachment($attachment_id, $size);

Remember to replace $attachment_id and $size with the their appropriate values. The following example pulls in the ‘large’ version of a featured image.

lazy_attachment(get_the_post_thumbnail($post->ID, 'large');

Leave a Reply

Your email address will not be published.

Are you in need of a freelance web developer?

Hire me