页面速度警告 - 在图像元素上使用明确的宽度和高度

问题描述 投票:0回答:5

我想使用 tailwind css 在我的网页中设置响应式图像。我提供了足够的类来使其在不同的屏幕尺寸上工作。现在我在页面速度方面遇到以下错误。

如何消除警告?

css image tailwind-css pagespeed web-performance
5个回答
1
投票

背景

此警告的存在是为了防止图像加载时布局发生变化。目前,图像的类别为

w-5/6 mx-auto
。这足以使图像具有响应能力,但在加载图像之前,浏览器不知道图像有多高。因此,当图像加载时,将会出现布局偏移。

然后,您需要告诉浏览器图像在加载之前应该有多宽和高。有几种方法可以做到这一点。 已知尺寸

如果您知道图像的高度,我建议您遵循 fromaline 的答案。

<img src='assets/image/brainstorm.svg' alt='nature' class='w-5/6 mx-auto border' width='300' height='300' />

因为我们已经用 
w-5/6

定义了显示宽度,所以图像将具有响应能力。然后将

width='300'
height='300'
属性用于纵横比。
这里有一个来自 Tailwind Playground 的链接,向您展示它如何实现响应式并消除布局偏移:

https://play.tailwindcss.com/rjz9ylFNl5?size=482x720

尺寸未知

如果您不知道图像的宽度和高度

并且

您需要它们具有响应能力,则本质上您需要创建一个具有固定宽高比的容器。我建议查看纵横比插件 <div class='w-5/6 aspect-w-16 aspect-h-9 mx-auto'> <img src='assets/image/brainstorm.svg' alt='nature' class='object-cover w-full h-full' /> </div>

再次提供 Tailwind Playground 演示的链接:
https://play.tailwindcss.com/2zmPJixbrO?size=584x720


1
投票
顺风纵横比

。 效果很好


0
投票


0
投票

首先确定原始图像的尺寸 - 通过查看您拉入的原始图像或使用浏览器开发工具查看它呈现的尺寸。尺寸本身并不重要,因为浏览器使用它们来计算纵横比。使用

width

height
属性添加这些尺寸,然后将
img-fluid
类添加到图像:
<img src="..." class="img-fluid" width="300" height="300" />



-1
投票
width

height
来消除此警告,如下所示:
<img loading="lazy" src="assets/image/brainstorm/svg" alt="brainstorm" width="400" height="200" class="w-5/6 mx-auto" />

基本上,直接将 
width

height
添加到 html
img
标签可以防止布局变化,即使
img
尚未加载。当
img
延迟加载时,这一点尤其重要。更多信息
这里

© www.soinside.com 2019 - 2024. All rights reserved.