How can I detect the first section in liquid to prevent image lazy loading?

How can I detect the first section in liquid to prevent image lazy loading?

twilson90
Shopify Partner
32 0 19

I have multiple sections that constitute a template

In liquid I need to know the section that appears first so I can explicitly tell it NOT to lazy load images.

I was hoping a property like `section.index` existed but it does not.
I don't want to have to create a setting in each of my section schemas to toggle on/off lazy loading that I have to manually set depending on its order on the page.

 

I thought I could possibly have a variable increment at the beginning of each section, but then I realised that those variables don't carry over to other sections, only snippets.

 

Any ideas?

Replies 4 (4)

rigel_M
Shopify Partner
3 0 1

Hello there,

I have also been trying to use this property without success. There is no mention of it in the Liquid docs, if I'm not mistaken.

However, one of the latest Shopify blog post does mention this property which, in theory, should exist. 

https://www.shopify.com/partners/blog/shopify-storefronts-have-gotten-more-than-30-faster 

 

rigelM_0-1692708105001.png

So now, I'm as confused as you are. Hopefully someone can clear this up?

MaxDesign
Shopify Partner
213 15 84

As far as I'm concerned it works this way:

 

{% if section.index > 1 %}
  {%- assign loading = 'lazy' -%}
{% else %}
  {%- assign loading = 'auto' -%}
{% endif %}

{{- img | image_url: width: 500 | image_tag:
   class: 'my-class',
   loading: loading,
   alt: img.alt | escape
-}}

 

The downside is that you can't target a section group. Which means that the first section of the "footer" section group will return an index of 1, but since it's the footer its not relevant to eager load. This feature seems half baked like many new feature release, but it's in its infancy so they might improve it.

We'd need something along these lines but unfortunately not possible at the moment:

 

{% if section.group.index > 1 or section.index > 1 %}
  {%- assign loading = 'lazy' -%}
{% else %}
  {%- assign loading = 'auto' -%}
{% endif %}

 

Reach out to me at admin@maxdesign.expert
rigel_M
Shopify Partner
3 0 1

Thanks @MaxDesign . It works now on its own and this has also been added to the Liquid documentation (last time I checked at the time of my previous comment, it wasn't)

rigel_M_0-1695042206386.png

https://shopify.dev/docs/api/liquid/objects/section

rigel_M
Shopify Partner
3 0 1

It seems we can also target section groups now so it should take care of your concerns about section groups.