首页 > 解决方案 > 核心网络生命体征标记的图像元素没有明确的宽度和高度

问题描述

我在 PageSpeed 洞察力上检查 Core Vitals 并注意到它的标记 Image elements do not have explicit width and height和建议Set an explicit width and height on image elements to reduce layout shifts and improve CLS.

我不确定它的确切含义以及我可以做些什么来解决这个问题,具体到我的情况

<img src="someimage.jpg" width="100%" height="100%" alt="something" class="img-responsive">

我的页面是响应式的,我正在为这个网页使用 bootstrap v3.x,因为它是旧页面。因为页面是响应式的,并且我正在使用 class="img-responsive" 来自动调整图像大小,但这会影响 CLS 等核心关键。

由于布局是响应式的,因此定义使用图像以避免 CLS 问题的最佳方法是什么。

我注意到 Page Speed Insigh 报告的大部分 CLS 都是针对 owl Carousal

以下是为图像生成 CLS 问题的代码副本

<div class="container">
  <div class="row">
    <div class="col-md-12 col-lg-12 lc-hp-col">
      <div class="owl-carousel owl-theme" data-items="1" data-items-desktop="1" data-items-tablet="[991,1]" data-items-mobile="[767,1]" data-pagination-speed="200" data-auto-play="true" data-stop-on-hover="true">
        <div class="item">
          <img alt="ALT" class="img-responsive" src="https://dummyimage.com/992x588/000/3431af&text=IMAGE+1">
        </div>
        <div class="item">
          <img alt="ALT" class="img-responsive" src="https://dummyimage.com/992x588/000/3431af&text=IMAGE+2">
        </div>
        <div class="item">
          <img alt="ALT" class="img-responsive" src="https://dummyimage.com/992x588/000/3431af&text=IMAGE+3">
        </div>
        <div class="item">
          <img alt="ALT" class="img-responsive" src="https://dummyimage.com/992x588/000/3431af&text=IMAGE+4">
        </div>
        <div class="item">
          <img alt="ALT" class="img-responsive" src="https://dummyimage.com/992x588/000/3431af&text=IMAGE+5">
        </div>
      </div>
    </div>
  </div>
</div>

CodePen链接

一些文章建议将 scrset 用于响应式图像,但这并不实用,因为我们必须上传同一图像的多个版本。

<img
  width="1000"
  height="1000"
  src="puppy-1000.jpg"
  srcset="puppy-1000.jpg 1000w, puppy-2000.jpg 2000w, puppy-3000.jpg 3000w"
  alt="Puppy with balloons"
/>

标签: htmlcssseogoogle-search-consolecore-web-vitals

解决方案


除了您提到的 srcset 解决方案之外,这个问题没有真正的解决方案。除非您指定图像尺寸,否则可能会标记布局偏移问题。

我同意多种图像尺寸的整合是困难和麻烦的,也许并不总是合理的。即使您集成了多种尺寸的图像,如果图像设置为响应于任何尺寸而不仅仅是一组选项,您仍然可以进行布局转换。

如果您的图像开始非常快速地加载,那么 CLS 不太可能被 Google 标记(或打扰任何用户),以便在布局有机会完全渲染(并因此转移)之前知道图像大小。尽可能推迟任何事情,以将图像带到线路的最前面。

这可能有问题,但我实现了一个生成的小 png 来快速加载图像数据,如下所示:

<img class="img_scale"
    src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" 
    data-src="/img/img.jpg"
/>

您还可以使用 csscalc 来估计图像容器的百分比、像素值或 em 值,以大大减少移位量。如果不使用静态尺寸,您可能无法消除它,但您可以将其减少。


推荐阅读