当PageSpeed Insights检测到网页包含阻止呈现的外部样式表(该样式表会延迟在屏幕上显示内容的时间)时,就会触发此规则。

概览

屏幕显示内容之前,浏览器会阻止外部CSS文件。这会导致额外的网络延迟,并延长屏幕显示内容的时间。

建议

如果外部CSS资源较小,您可以直接将这些内容插入到HTML文档中,这称为“内嵌”。通过这种方式内嵌较小CSS资源,浏览器可以继续呈现网页。请注意,如果CSS文件较大,完全内嵌CSS可能会导致PageSpeed Insights通过按优先级排列可见内容警告您网页的首屏部分体积过大。如果CSS文件较大,您需要识别和内嵌呈现首屏内容所需的CSS,并暂缓加载其余样式,直到首屏内容显示之后为止。

内嵌较小CSS文件的示例

如果HTML文档如下所示:

 
<html>
  <head>
    <link rel="stylesheet" href="small.css">
  </head>
  <body>
    <div class="blue">
      Hello, world!
    </div>
  </body>
</html>

并且small.css资源如下所示:


 
  .yellow {background-color: yellow;}
  .blue {color: blue;}
  .big { font-size: 8em; }
  .bold { font-weight: bold; }

您就可以内嵌关键的CSS,具体方法如下:


 
<html>
  <head>
    <style>
      .blue{color:blue;}
    </style>
    </head>
  <body>
    <div class="blue">
      Hello, world!
    </div>
  </body>
</html>
<link rel="stylesheet" href="small.css">

在网页加载之后,原始small.css才会加载。通过JavaScript将所有<style><link>元素插入到文档中,以维护CSS规则的应用顺序。

请勿内嵌较大数据URI

在CSS文件中内嵌数据URI时,请务必慎重。您可以在CSS中选择使用较小数据URI,因为内嵌较大数据URI会导致首屏CSS变大,进而延缓网页呈现时间。

请勿内嵌CSS属性

应尽量避免在HTML元素(例如,< p style=...>)中内嵌CSS属性,因为这经常会导致出现多余的重复代码。此外,内容安全政策(CSP)会在默认情况下阻止在HTML元素上内嵌CSS。

 

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 3.0 License, and code samples are licensed under the Apache 2.0 License. For details, see our Site Policies.