Search code examples
reactjsimagegatsbypreloadgatsby-image

GatsbyJS: Preload critical masthead image


I am having an issue on my site where my above-the-fold masthead image comes in way too late which makes the site feel slow. The site is built with GatsbyJS where I am using the Gatsby Image plugin as well. I have tried with rel="preload as="image" but this didn't seem to do any difference:

<Img
          fluid={
            wpgraphql.imageFile.childImageSharp.fluid
          }
          id="hero__image"
          style={{
            position: "initial"
          }}
          rel="preload"
          as="image"
        />

After reading the Gatbsy Image documentation I found that loading="eager" could make a difference as well. I therefore have tried adding the loading="eager" but still my masthead image is one of the last things to be discovered in my waterfall.

How can I make my masthead image load critical and come in earlier in my waterfall?


Solution

  • Gatsby Image uses a low-quality preview image in the src and delays the switch from this preview image to the full-size image until Gatsby is initialized client-side (which happens after React hydrates). For this reason it's never going to be particularly performant for above-the-fold content. I recommend using the srcSet data that comes back from the query you have now directly:

    <img
      srcSet={wpgraphql.imageFile.childImageSharp.fluid.srcSet}
      alt=""
      loading="eager"
    />
    

    From here you can style it to match your desired output.