≪ Today I learned.
RSS購読
    公開日
    タグ
    HTML
    著者
    ダーシノ

    Google Fontsのrender-blockingを解消する

    このページをLighthouseで計測すると、以下のような警告が表示される。

    Eliminate render-blocking resources Potential savings of 680 ms

    Google Fonts [Cdn] 30.6 KiB 1,000 ms

    TL;DR

    dns-prefetchpreconnectを使う

    Google Fontsはhttps://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@100..900&display=swapから読み込んでいる。このURLには大量のCSSが含まれており、その中からfonts.googleapis.comhttps://fonts.gstatic.comにアクセスしフォントをダウンロードしている。

    /* [0] */
    @font-face {
      font-family: 'Noto Sans JP';
      font-style: normal;
      font-weight: 100 900;
      font-display: swap;
      src: url(https://fonts.gstatic.com/s/notosansjp/xxx.0.woff2) format('woff2');
      unicode-range: ...;
    }
    /* [1] */
    @font-face {
      font-family: 'Noto Sans JP';
      font-style: normal;
      font-weight: 100 900;
      font-display: swap;
      src: url(https://fonts.gstatic.com/s/notosansjp/xxx.1.woff2) format('woff2');
      unicode-range: ...;
    }
    /* [2] */
    @font-face {
      font-family: 'Noto Sans JP';
      font-style: normal;
      font-weight: 100 900;
      font-display: swap;
      src: url(https://fonts.gstatic.com/s/notosansjp/xxx.2.woff2) format('woff2');
      unicode-range: ...;
    }
    ...

    別オリジンのドメイン名からIPアドレスに名前解決する必要があり、時間を要してしまう。rel=“dns-prefetch”をすることで、あらかじめブラウザに名前解決をさせることで高速化できるというもの。

    さらに踏み込んでrel="preconnect"を使うと名前解決に加え、TCP接続の確立やTLSハンドシェイクを事前に行うことができる。別オリジンへのリクエストの遅延を最小化できる。

    <link rel="dns-prefetch" href="https://fonts.googleapis.com" />
    <link rel="dns-prefetch" href="https://fonts.gstatic.com" crossorigin />
    <!-- or -->
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />

    その他の最適化方法