skip to Main Content

I wish to add lazy loading to the images on my webpage however I’ve been having some issues. I’ve been using this guide: (https://speedboostr.com/shopify-lazy-loading/). I’ve done everything correctly so far and some images have been working except for the following code:

<div class="product-item {{ variant.id }}">
  <div class="product-item__thumb">
    {%- if product.images.size > 1 -%}
    <a href="{{ product.url | within: collection }}">
      <img class="thumb-primary popup_cart_image""lazyload" src="{{ product.featured_image.src | img_url: 'grande' }}" alt="{{ product.featured_image.alt }}">
      {%- for image in product.images limit: 1 offset: 1 -%}
      <img class="thumb-secondary popup_cart_image""lazyload" src="{{ image.src | img_url: 'grande' }}" alt="{{ product.featured_image.alt }}">
      {%- endfor -%}
    </a>
    {%- else -%}
    <a href="{{ product.url | within: collection }}">
      <img class="popup_cart_image""lazyload" src="{{ product.featured_image.src | img_url: 'grande' }}" alt="{{ product.featured_image.alt }}">
    </a>
    {%- endif -%}
  </div>

3

Answers


  1. I would do this via Javascript. Let’s suppose that you have a function that receives a context and a URL, like

    function generatePicture(context, url) {
        context.innerHTML += `<img src="${url}">`;
    }
    

    Let’s suppose further that you have an attribute of img-url="someurl" wherever you might need to lazyload images later. Then you can do something like this upon page load:

    for (let context of document.querySelectorAll("[img-url]")) generatePicture(context, context.getAttribute("img-url"));
    

    However, this is technically not yet a lazy-loading. Something needs to trigger the image loading, but it’s unclear what should trigger it. Above we assume that the page load’s end should trigger the load of all images, but you may need to change this and apply the triggering logic that you prefer.

    Login or Signup to reply.
  2. You should be able to just add the loading="lazy" attribute to the image

    Login or Signup to reply.
  3. You can simply add loading attribute.

    <img
            srcset="{{ image | img_url: '375x' }} 375w,
              {{ image | img_url: '750x' }} 750w,
              {{ image | img_url: '1100x' }} 1100w,
              {{ image | img_url: '1500x' }} 1500w,
              {{ image | img_url: '1780x' }} 1780w,
              {{ image | img_url: '2000x' }} 2000w,
              {{ image | img_url: '3000x' }} 3000w,
              {{ image | img_url: '3840x' }} 3840w,
              {{ image | img_url: 'master' }} {{ image.width }}w"
            sizes="auto"
            src="{{ image | img_url: '2000x' }}"
            loading="lazy"
            alt="{{ image.alt | escape }}"
    >
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search