[SOLVED] Lazyloading images with data-src and data-srcset

Hey folks!

Recently came across a great way to get lazy loading of images working the way I have been envisioning for some time. Figured I would post here to help others who want to accomplish the same on their sites.

This is just a quick overview of how I implemented lazysizes.js with my portfolio template I have been working on for a client.

My twig code looks like this now:

  {% set service_image = null %} {# set to null for it to pass in for loop below #}
  {% for featuredimage in page.header.project_featured_image %}
    {% set service_image = page.media[featuredimage.name].derivatives(640, 1024, 200).sizes('(min-width:1024px) 1024px, 100vw') %}
    <img class="lazyload" data-src="{{ service_image.url(false) }}" data-srcset="{{ service_image.srcset(false) }}">
  {% endfor %}

I wasn’t aware that I needed to set a variable as a null outside of a for loop so that it actually registers the variable.

Since I also wanted to grav’s derivatives for responsive-ness I found a great minimal solution without the need to modify any of gravs existing codebase and it does work out quite well :slight_smile:

If anyone needs any help with this feel free to respond!

Hi, since you asked, I’m new to this and I’d love some more information about you implemented this! I gather this code goes into the twig file, does it also play nice with modular pages? Presumably the JavaScript code has to go somewhere too? Does it then load all images lazily, or do you have to specify in the markdown as well?