我该如何向该图像添加懒散的文字



我想在网页上的图像中添加延迟加载,但我遇到了一些问题。我一直在使用此指南:(https://speedboostr.com/shopify-lazy-loading/)。到目前为止,我已经正确地完成了所有操作,除了以下代码外,一些图像一直在工作:

<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>

我会通过Javascript来实现这一点。假设您有一个function,它接收context和一个URL,如

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

让我们进一步假设,您有一个属性img-url="someurl",无论您以后可能需要对图像进行懒散处理。然后你可以在页面加载时做这样的事情:

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

然而,从技术上讲,这还不是一个懒惰的加载。需要触发图像加载,但不清楚应该由什么触发。上面我们假设页面加载结束时应该触发所有图像的加载,但您可能需要更改这一点,并应用您喜欢的触发逻辑。

您应该能够添加loading="懒惰;图像的属性

您可以简单地添加加载属性。

<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 }}"
>