Stock Luma product page serves a 700 by 700 gallery image into a 382 by 382 box on mobile, roughly 70 percent of the bytes thrown away; fix with view.xml sizes, an LCP image that is not lazy-loaded, and a preload

Magento 2 Lazy Loading: Eager LCP, srcset, Preload

Magento 2 lazy-loads the first product image on a category page, the one that is almost always the Largest Contentful Paint element. Because the template hardcodes it, no config switch turns it off. This article leads a Magento frontend developer through the template-level fix: eager-load the first row, give the browser a srcset it can choose from, and preload the product-page image, without an extension and with one uploaded image per product.

TL;DR — image_with_borders.phtml hardcodes loading="lazy" on every catalog image in both 2.4.8-p5 and 2.4.9. Pass srcset, sizes, fetchpriority and loading through the third argument of getImage(), override that template so the passed loading replaces the hardcoded one, and preload the product image from a block in head.additional, because layout XML rejects as="image" in developer mode. Cost: one small template override to re-check per upgrade.

Why Magento lazy-loads its own LCP image

The baseline is core’s catalog image template. This is the same file in 2.4.8-p5 and 2.4.9:

// vendor/magento/module-catalog/view/frontend/templates/product/image_with_borders.phtml
<img class="<?= $escaper->escapeHtmlAttr($block->getClass()) ?>"
    <?php foreach ($block->getCustomAttributes() as $name => $value): ?>
        <?= $escaper->escapeHtmlAttr($name) ?>="<?= $escaper->escapeHtml($value) ?>"
    <?php endforeach; ?>
    src="<?= $escaper->escapeUrl($block->getImageUrl()) ?>"
    loading="lazy"
    width="<?= $escaper->escapeHtmlAttr($block->getWidth()) ?>"
    height="<?= $escaper->escapeHtmlAttr($block->getHeight()) ?>"

loading="lazy" has no condition and no config path. Every tile in a category grid gets it, including the first one, which on a stock Luma category page is the LCP element. Magento LCP Images measured what that costs on 2.4.8-p5: 420 ms of resource load delay against 50 ms of actual download. Lighthouse flags it as "LCP image was lazily loaded" in its LCP request discovery insight.

The product page is different. gallery.phtml renders a placeholder <img class="gallery-placeholder__image"> with the main image in the HTML, width and height set and no loading attribute, so the image is not lazy. What it lacks is priority: it sits in the body, behind the header’s CSS and scripts, with no fetchpriority. The two pages need two different fixes.

The size is wrong too. Luma’s etc/view.xml declares the sizes, and the merchant never chooses them:

<!-- vendor/magento/theme-frontend-luma/etc/view.xml -->
<image id="category_page_grid" type="small_image">
    <width>240</width>
    <height>300</height>
</image>
<image id="product_page_image_medium" type="image">
    <width>700</width>
    <height>700</height>
</image>

On the stock product page that 700×700 file renders into a 382×382 box on mobile:

Lighthouse image delivery audit on a stock Luma product page: a 23.6 KiB gallery image at 700x700 displayed at 382x382, 16.5 KiB estimated savings

Roughly 70% of those bytes are thrown away. The JPEG is already reasonably compressed, so a better codec would save little. What is missing is a srcset that lets the browser ask for the size it will actually paint.

Eager-load the first row with a small override

Look at the loop above loading="lazy": getCustomAttributes() renders whatever array you pass as the third argument of getImage(), verbatim, onto the tag:

// Magento\Catalog\Block\Product\AbstractProduct
public function getImage($product, $imageId, $attributes = [])
{
    return $this->imageBuilder->create($product, $imageId, $attributes);
}

Custom attributes are emitted before the hardcoded loading="lazy", and the HTML parser keeps the first occurrence of a duplicated attribute. So passing 'loading' => 'eager' in that array already works: Chrome reports img.loading === "eager" for the first tile on the rendered 2.4.8-p5 page.

I would still not ship it. The markup then carries two contradictory loading attributes, and the next developer has no way to tell the duplicate is deliberate. Override the template instead.

The tempting one-liner, loading="<?= $block->getData('loading') ?: 'lazy' ?>", does not work. ImageFactory::create() stores everything you pass under custom_attributes, so getData('loading') is always null. Rendered on 2.4.8-p5 with 'loading' => 'eager', it produces loading="eager" fetchpriority="high" src="…" loading="lazy", the same duplicate as before. Take loading out of the custom attributes and print it once:

// app/design/frontend/Vendor/theme/Magento_Catalog/templates/product/image_with_borders.phtml
// Copied from core. Three changes: the three lines below, the loop variable, the loading line.
$customAttributes = $block->getCustomAttributes();
$loading = $customAttributes['loading'] ?? 'lazy';
unset($customAttributes['loading']);
?>
...
            <?php foreach ($customAttributes as $name => $value): ?>
...
            loading="<?= $escaper->escapeHtmlAttr($loading) ?>"

Rendered on 2.4.8-p5, the first tile gets fetchpriority="high" src="…" loading="eager", and a tile without the attribute keeps loading="lazy". Core’s lazy stays the default, which is the right answer below the fold. width and height still come from the block, so the reserved box stays and CLS does not move.

Add srcset and sizes from view.xml

The extra sizes are data, not uploads. Image roles are pointers, not copies: Base, Small, Thumbnail and Swatch in Images and Videos all point at the one uploaded file, and every <image id> in view.xml tells Magento how to derive a cached variant from it. One upload, as many sizes as you declare:

<!-- app/design/frontend/Vendor/theme/etc/view.xml -->
<image id="category_page_grid_400" type="small_image">
    <width>400</width>
    <height>500</height>
</image>
<image id="category_page_grid_600" type="small_image">
    <width>600</width>
    <height>750</height>
</image>

New uploads are resized on first request. Existing products keep serving the old cache until you regenerate it, and a changed view.xml takes effect only after a cache flush:

bin/magento catalog:images:resize
bin/magento cache:flush

The resize walks the whole catalog, so it belongs in a deploy step or an off-hours run.

The srcset is then built in the listing template, where the product is in scope, and goes through the same attributes argument:

// app/design/frontend/Vendor/theme/Magento_Catalog/templates/product/list.phtml
$position = 0;
foreach ($_productCollection as $_product):
    // Each id is an <image id="..."> entry in the theme's etc/view.xml.
    $srcset = [];
    foreach (['category_page_grid_400', 'category_page_grid_600'] as $variantId) {
        $variant = $block->getImage($_product, $variantId);
        $srcset[] = $variant->getImageUrl() . ' ' . (int) $variant->getWidth() . 'w';
    }

    $aboveFold = $position < 2;   // first row on mobile; match your grid
    $productImage = $block->getImage($_product, $imageDisplayArea, [
        'srcset'        => implode(', ', $srcset),
        'sizes'         => '(max-width: 600px) 45vw, (max-width: 1024px) 30vw, 240px',
        'fetchpriority' => $aboveFold ? 'high' : 'auto',
        'loading'       => $aboveFold ? 'eager' : 'lazy',
    ]);
    $position++;

Verified on 2.4.8-p5, the first tile then renders:

<img class="product-image-photo"
     srcset="...-400.jpg 400w, ...-600.jpg 600w"
     sizes="(max-width: 600px) 45vw, (max-width: 1024px) 30vw, 240px"
     fetchpriority="high"
     src="..." loading="eager" width="240" height="300" alt="Joust Duffle Bag"/>

One trap: getImage() and getProduct() live on Magento\Catalog\Block\Product\AbstractProduct, which the listing block extends. They are not on Magento\Catalog\Block\Product\Image, the $block inside image_with_borders.phtml. Calling them there does not fail loudly: DataObject::__call turns getImage() into getData('image'), returns null, and the page renders with an empty srcset. Build the attributes in list.phtml, never in the image template.

Preload the product image

On the product page the job is priority, not discovery: a <link rel="preload" as="image" fetchpriority="high"> in <head> starts the request before the browser has parsed the body. The obvious way to add it is layout XML, and that is the trap. head.xsd restricts as to three values, unchanged in 2.4.9:

<!-- vendor/magento/framework/View/Layout/etc/head.xsd -->
<xs:attribute name="as">
    <xs:simpleType>
        <xs:restriction base="xs:string">
            <xs:enumeration value="font" />
            <xs:enumeration value="script" />
            <xs:enumeration value="style" />
        </xs:restriction>
    </xs:simpleType>
</xs:attribute>

A preload without as is ignored by the browser, and as="image" fails validation, but only sometimes. Layout\Merge::_validateMergedLayout() rethrows a validation failure only in developer mode:

// vendor/magento/framework/View/Model/Layout/Merge.php
if ($this->appState->getMode() === \Magento\Framework\App\State::MODE_DEVELOPER) {
    throw $e;
}

So as="image" renders fine on a production-mode install (verified on 2.4.8-p5: it emits <link rel="preload" as="image" href="..." /> as written) and then throws on the first developer-mode machine or CI job that merges the same layout. A bug that works in production and fails in development is the worst way round. The image URL is per product and only known at render time anyway, which no static layout entry can express. Use a block.

Four files:

app/code/Vendor/LcpPreload/
├── registration.php
├── etc/module.xml
├── Block/ProductImagePreload.php
└── view/frontend/
    ├── layout/catalog_product_view.xml
    └── templates/preload.phtml
<!-- view/frontend/layout/catalog_product_view.xml -->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="head.additional">
            <block class="Vendor\LcpPreload\Block\ProductImagePreload"
                   name="lcp.image.preload"
                   template="Vendor_LcpPreload::preload.phtml"/>
        </referenceBlock>
    </body>
</page>
// Block/ProductImagePreload.php - returns the URL the gallery placeholder uses
class ProductImagePreload extends \Magento\Catalog\Block\Product\AbstractProduct
{
    public function getImageUrl(): ?string
    {
        $product = $this->getProduct();
        if ($product === null) {
            return null;
        }

        return $this->getImage($product, 'product_page_image_medium')->getImageUrl();
    }
}
<?php /** @var \Vendor\LcpPreload\Block\ProductImagePreload $block */ ?>
<?php if ($url = $block->getImageUrl()): ?>
<link rel="preload" as="image" fetchpriority="high"
      href="<?= $escaper->escapeUrl($url) ?>">
<?php endif; ?>

Extending AbstractProduct supplies both getProduct() and getImage(), so the block needs no constructor and no Magento\Framework\Registry, which is @deprecated 102.0.0.

The preload only helps if it requests byte-for-byte the same URL as the placeholder; otherwise the browser downloads the image twice. Both resolve the product_page_image_medium id, so they match. 2.4.9 moved the placeholder URL into a new view model, Magento\Catalog\ViewModel\Product\Gallery, which appends ?___store=<code> when Add Store Code to URLs is on. Run against 2.4.9 with that setting on, getImage() returns the same suffix, so the URLs still match. If your theme replaces the gallery, check the two URLs on a rendered page before you trust the preload.

Keeping CLS at zero

Magento already emits width and height from the view.xml entry on catalog images and on the gallery placeholder. That is why the stock pages measured CLS 0 before any of this work. Two things undo it: an override that drops those attributes, and CMS or Page Builder images where no view.xml entry applies. Check both after the change.

The tradeoff: every template you override is one you carry

Theme overrides are the part of a Magento build that ages. Core’s file changes in a patch release, your copy keeps the old version, and you inherit whatever bug the change fixed. Measured against that, this approach is cheap on purpose:

  • srcset, sizes and fetchpriority need no override. They go through getImage()‘s attributes argument, a supported extension point.
  • loading costs a five-line diff in image_with_borders.phtml, the only thing core hardcodes after the attribute loop. A diff that small is easy to re-apply.
  • Override only templates that render an LCP element: the category grid and the product gallery. Below the fold, core’s loading="lazy" is correct.
  • Keep widths in view.xml, not in markup. Widths declared as data survive a template re-diff.

image_with_borders.phtml is identical in 2.4.8-p5 and 2.4.9, so the override carried across that upgrade unchanged.

Here is a working example, step by step

#StepWhere it lives
1Declare the widths the theme rendersyour theme’s etc/view.xml
2Emit srcset, sizes, fetchpriority and loading for the first rowlist.phtml, via getImage()‘s third argument
3Let the passed loading replace core’ssmall override of image_with_borders.phtml
4Preload the product-page imagea block in head.additional
5Regenerate the image cachecatalog:images:resize in the deploy

There is no <picture> element in that list. Format selection (WebP, AVIF) belongs on the server: the BroCode WebP/AVIF image optimizer writes sidecar files and nginx picks one by Accept. Adding <source type="image/avif"> on top would duplicate that in markup and double the URLs every template builds. Use <picture> for art direction, meaning a different crop on mobile.

Verification: did the markup do anything?

Run the LCP check first, before changing anything. If the LCP element is a webfont heading rather than a product image, no image work will move it:

// Paste in the console on the page you are optimising.
new PerformanceObserver((list) => {
  const e = list.getEntries().at(-1);
  console.log('LCP', Math.round(e.startTime), 'ms', e.element);
}).observe({ type: 'largest-contentful-paint', buffered: true });

Then, after the change:

1. Lighthouse, LCP request discovery: "lazy load not applied" and "fetchpriority=high applied" both ticked on the category page.

2. DevTools Network, Img filter, mobile viewport: the downloaded width is no more than about twice the CSS box. More than that means sizes does not match the layout.

3. Product page, Network: the gallery image appears once, started from the preload, not twice.

Pass criteria: the LCP image is neither lazy nor discovered late, no image transfers at more than roughly twice its displayed width, every <img> still carries width and height, and CLS stays at zero.

Related reading

Sources & References

Disclaimer

The template and layout behaviour described here was run on a stock 2.4.8-p5 with sample data in production mode (August 2026). It was re-checked on 2.4.9 in November 2026: the catalog template, head.xsd and the developer-mode rethrow are unchanged, and the preload and placeholder URLs match with store codes in URLs both off and on. Core templates change between patch releases, so diff image_with_borders.phtml and gallery.phtml against your own version before relying on this.

← Previous
Next →

Written in collaboration with AI (Claude, by Anthropic). Ideas, verification, and accountability are mine; research and drafting are AI-assisted. Full disclosure → · Found an error? Tell me.