首页 > 解决方案 > 最大的内容绘画是一个大盖茨比背景图像,非常慢

问题描述

对于那些在这个问题上磕磕绊绊想知道如何提高他们的灯塔分数的人,我在另一个问题上发布了关于这个主题的答案,其中包含许多一般提示。


我正在运行 PageSpeed 洞察,我最大的问题是最大的内容绘制,大约 8-10 秒。下面他们列出了我最大的内容绘画元素

Largest Contentful Paint element 1 element found
This is the largest contentful element painted within the viewport. Learn More
Element

This is the a paragraph that appears above here    
<section class="mainBgImage gbi--716926567-eDXcajFRMpQ2F1s7wNgLk1" style="background-position:center top;background-repeat:no-repeat;background-size:cover;position:relative;opacity:0.99" role="img">

这个元素是一个在背景中跨越我整个网站的图像。它最初是一个 1.2 MB png,我使用...GatsbyImageSharpFluid_withWebp_noBase64maxWidth 为 1950 加载。

这是我如何渲染它的代码

    import BackgroundImage from 'gatsby-background-image';

    ...

      <BackgroundImage
        Tag="section"
        role="img"
        className='mainBgImage'
        fadeIn={false}
        // style={{objectFit: 'contain',  width: '100%' }}
        style={{
          opacity: 0.03,
          backgroundPosition: "center top",
          
        }}
        fluid={wheatImgProps}
      >
          {children}
      </BackgroundImage>

这是静态的graphql查询

    const data = useStaticQuery(graphql
        `query LayoutQuery {
          wheatImg: file(
            extension: {regex: "/(jpg)|(jpeg)|(png)/"},
            name: {eq: "wheat-background"}
          ) {
            childImageSharp {
              fluid(maxWidth: 1950) {
                ...GatsbyImageSharpFluid_withWebp_noBase64
              }
            }
          }
        }
        `
      )

标签: reactjsgatsbypagespeedpagespeed-insightsgatsby-image

解决方案


原来解决方案是将我的背景图像分成 2 个。一个用于“首屏”(无需滚动即可看到),一个用于“首屏”。我还发现这个图像压缩器网站在减少文件大小方面是最有帮助和最直接的网站之一。

然后我创建了一个绝对定位的 div 看起来像

const BGImg = ({img, className}:{img:FluidObject, className?:string}) => (
    <Img
        Tag="section"
        className={className}
        durationFadeIn={250}
          
        style={{
            opacity: 0.03,
            minWidth:"100%",
            objectFit: 'cover',
            objectPosition: "center top",
        }}
        fluid={img}
    />
)

...

<div id='layout'>
    <div id='bgImageContainer'>
        <BGImg img={above_the_fold_bg} />
        <BGImg img={below_the_fold_bg}  />
    </div>
...

造型看起来像

#bgImageContainer{
    position: absolute;
    z-index: -999;
    min-width:100%;
    min-height:100%;
    display:flex;
    flex-direction: column;
    justify-content: flex-end;
    align-self: stretch;
}

#layout{
    overflow: hidden;
    position: relative;
}

推荐阅读