Home > Software engineering >  How can I add lazyloading to this image?
How can I add lazyloading to this image?

Time:01-07

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 >
  <div >
    {%- if product.images.size > 1 -%}
    <a href="{{ product.url | within: collection }}">
      <img "lazyload" src="{{ product.featured_image.src | img_url: 'grande' }}" alt="{{ product.featured_image.alt }}">
      {%- for image in product.images limit: 1 offset: 1 -%}
      <img "lazyload" src="{{ image.src | img_url: 'grande' }}" alt="{{ product.featured_image.alt }}">
      {%- endfor -%}
    </a>
    {%- else -%}
    <a href="{{ product.url | within: collection }}">
      <img "lazyload" src="{{ product.featured_image.src | img_url: 'grande' }}" alt="{{ product.featured_image.alt }}">
    </a>
    {%- endif -%}
  </div>

CodePudding user response:

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.

CodePudding user response:

You should be able to just add the loading="lazy" attribute to the image

  •  Tags:  
  • Related