I use the code below to display multiple images on one page. As you can see I use browser-side lazy loading via loading="lazy"
. This leads to the problem that my Largest Contentful Paint is loaded via lazy loading and this leads to poor performance.
I have tried the following so that the first image is not loaded with a delay via lazy loading:
<?php if($image->is($article->images()->first())): ?>
loading="eager"
<?php else: ?>
loading="lazy"
<?php endif ?>
This did not cause any errors, but also had no effect at all.
What would be the right way?
Many thanks in advance!
The entire code:
<ul class="gallery">
<?php foreach ($article->images() as $image) : ?>
<li>
<?php if ($image->orientation() == 'landscape') : ?>
<?php
$sizes = "
(min-width: 100rem) 40vw,
(min-width: 75rem) 50vw,
(min-width: 50rem) 60vw,
(min-width: 40rem) 70vw,
100vw";
if ($image = $image): ?>
<picture>
<source
srcset="<?= $image->srcset('avif') ?>"
sizes="<?= $sizes ?>"
type="image/avif"
>
<source
srcset="<?= $image->srcset('webp') ?>"
sizes="<?= $sizes ?>"
type="image/webp"
>
<img class="landscape"
loading="lazy"
alt="<?= $article->date()->toDate('Y m d') ?>"
title="<?= $article->date()->toDate('Y m d') ?>"
src="<?= $image->resize(400)->url() ?>"
srcset="<?= $image->srcset() ?>"
sizes="<?= $sizes ?>"
width="<?= $image->resize(2160)->width() ?>"
height="<?= $image->resize(2160)->height() ?>"
>
</picture>
<?php endif ?>
<?php else : ?>
<?php
$sizes = "
(min-width: 100rem) 25vw,
(min-width: 75rem) 30vw,
(min-width: 50rem) 35vw,
(min-width: 40rem) 40vw,
100vw";
if ($image = $image): ?>
<picture>
<source
srcset="<?= $image->srcset('avif') ?>"
sizes="<?= $sizes ?>"
type="image/avif"
>
<source
srcset="<?= $image->srcset('webp') ?>"
sizes="<?= $sizes ?>"
type="image/webp"
>
<img class="portrait"
loading="lazy"
alt="<?= $article->date()->toDate('Y m d') ?>"
title="<?= $article->date()->toDate('Y m d') ?>"
src="<?= $image->resize(400)->url() ?>"
srcset="<?= $image->srcset() ?>"
sizes="<?= $sizes ?>"
width="<?= $image->resize(2160)->width() ?>"
height="<?= $image->resize(2160)->height() ?>"
>
</picture>
<?php endif ?>
<?php endif ?>
</li>
<?php endforeach ?>
</ul>