Skip to content

Lazyload images

Maylis Agniel edited this page Aug 24, 2018 · 8 revisions

For lazyloading we use lazysizes.

app.js

import lazysizes from 'lazysizes'

functions.php

add_filter( 'timber/twig', function( \Twig_Environment $twig ) {
    // Handle lazysizes img src/srcset
    $twig->addFunction(new Timber\Twig_Function('lazy_src', function($field, $extra_class = ''){
        $image  = new Timber\Image($field['image']);
        $srcset = [];

        foreach (IMAGE_SIZES as $name => $width){
            array_push($srcset, $image->src($name).' '.$width.'w');   
        } 

        return 'data-srcset="'.join(',', $srcset).'" class="lazyload '.$extra_class.'"';
    }));  

    return $twig;
});

// Configure custom image sizes
DEFINE('IMAGE_SIZES', [
    'tablet' => 1088,
    'desktop' => 1280,
    'widescreen' => 1472,
    'fullhd' => 2000
]);

// Add custom image sizes to WP generation
foreach (IMAGE_SIZES as $name => $width){
    add_image_size($name, $width);  
}

Makefile

images: ## Regenerate images
  $(WPCLI) media regenerate --yes

Usage in Twig templates

{# For ACF field #}
<img {{lazy_src(post.get_field('some-group-with-an-image'))}} alt="">

Generate images

make images

Clone this wiki locally