reactjs - 最大的内容绘画是一个大盖茨比背景图像,非常慢
问题描述
对于那些在这个问题上磕磕绊绊想知道如何提高他们的灯塔分数的人,我在另一个问题上发布了关于这个主题的答案,其中包含许多一般提示。
我正在运行 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_noBase64
maxWidth 为 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
}
}
}
}
`
)
解决方案
原来解决方案是将我的背景图像分成 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;
}
推荐阅读
- html - 为什么 animate.css 仅适用于 DIV 元素
- javascript - 相同的承诺会产生两种不同的结果
- c++ - 不能引用隐式声明的函数 operator= - 它是一个已删除的函数
- apache-kafka - Apache Kafka - kafka-server-start.sh 没有开始
- python - Genshi:for循环插入换行符
- number-theory - 可被 d 整除且数字和等于 s 的最小正整数 n
- java - reactor-rabbitmq 是线程安全的吗
- java - Mojave 上缺少 MacOS Java 控制面板
- java - 如何为 postgres 数据库模式配置 JPA?
- react-native - 在 React Native 上向领域插入 100 万行的最快方法?