Member-only story
How to Lazy-Load Images in Drupal
Improve the performance of your site by loading only a few images at a time
When it comes to positioning a website, improving site speed is becoming increasingly important. But for certain sites it might not be that easy, it could be because it needs to render ads, a lot of scripts (for example for tracking), or other factors.
One thing I do in most of the sites I’m asked to improve is implementing lazy load on images. Lazy loading images means that instead of loading all the images on the page, you will only load the ones that become visible as you scroll. Doing just this you are likely to see a big increase in the Lighthouse report score.
Using template_preprocess_image(replacing mytheme with your theme name) is how you can easily implement this on your site:
/**
* Implements template_preprocess_image.
*
* @param array $variables
*/
function mytheme_preprocess_image(&$variables) {
// Add lazy loading attribute to all images.
$variables['attributes']['loading'] = 'lazy';
// Add width and height attributes.
$variables['attributes']['width'] = $variables['width'];
$variables['attributes']['height'] = $variables['height'];
}
It’s important to mention that to make this work, you will have to add width and height attributes…