How to preload largest-contentful-paint image in react helmet

Viewed 1705

I received this warning in lighthouse

enter image description here

I tried doing what that learn more link told me to do, and include a preload tag in the head for the image, but I still get the warning


I tried this preload tag, the url is the one which is in the browser when I right click the image and select "open in new tab"

<link rel="preload" as="image" href={`https://example.com:8080/src/assets/images/example.webp`} />

The image is just imported into the jsx component like import banner from "images/banner-large.png"; and then rendered with an image tag like <img src={example} className="w-100 banner-img" alt="Description" />


I'm also using img-optimizer-loaderto web-optimize my images and convert them to webp in my webpack config like below

{
    test: /\.(gif|png|jpe?g|webm|webp)$/i,
    use: [
      {
        loader: "img-optimize-loader",

        options: {
          compress: {
            // This will transform your png/jpg into webp.
            webp: {
              quality: 75,
            },
            disableOnDevelopment: true,
          },
          name: "[path][name].[ext]",
        },
      },
    ],
  },

It's worth noting that I import my images like

import image from 'src/assets/images/example.png'

but because of img-optimize-loader, all my images are converted to webp in the build, and the webp images are the ones displayed.

2 Answers

Import and use Helmet right inside your image component:

import { Helmet } from 'react-helmet'
import example from "images/example.png";


function Image () {
  return (
    <Helmet>
      <link rel="preload" as="image" href={example}>
    </Helmet>
  )
}
Related