サイト高速化にリソースヒントを活用

 



2019/10/17

リソースヒントとは?

HTTPリクエストにはDNSの解決など複数の処理が含まれており、処理内容が事前にわかればリクエスト時間の低減に繋がります。
そのための指示をHTML内で記述する方法が リソースヒント(Resource Hints) です。

サイト内で共通して使う外部リソースをあらかじめ解決しておき、表示の高速化などを図るのに役立ちますが、ブラウザの対応に依存します。
2019年10月時点ではIEやFirefoxなどがまだ完全には対応していませんが、将来的に実装されるであろう機能ですので、デメリットはあまりないと思います。

リソースヒント定義の種類

2019年10月時点で以下の種類があります。

DNS Prefetch

早めに解決すべきDNSを定義し、あらかじめDNS解決(ドメインとIPアドレスを紐づける処理)します。

The dns-prefetch link relation type is used to indicate an origin that will be used to fetch required resources, and that the user agent SHOULD resolve as early as possible. 2.1 DNS Prefetch

記述例

<link rel="dns-prefetch" href="//example.com">

Preconnect

ページ遷移先に必要なリソース(ファイル)に対し、あらかじめDNS解決、TCPハンドシェイク(接続の確立)、TLSネゴシエーション(証明書解決)などを行う定義です。

The preconnect link relation type is used to indicate an origin that will be used to fetch required resources. Initiating an early connection, which includes the DNS lookup, TCP handshake, and optional TLS negotiation, allows the user agent to mask the high latency costs of establishing a connection. 2.2 Preconnect

記述例です。crossorigin属性については以下をご参考ください。
crossorigin 属性: コンテンツへの CORS アクセスの要求 | MDN

<link rel="preconnect" href="//example.com">
<link rel="preconnect" href="//cdn.example.com" crossorigin>

Prefetch

次の遷移先にで使用する可能性のあるリソースをあらかじめダウンロードさせる定義です。

The prefetch link relation type is used to identify a resource that might be required by the next navigation, and that the user agent SHOULD fetch, such that the user agent can deliver a faster response once the resource is requested in the future. 2.3 Prefetch

以下のように次のページ自体や、そこで使うリソースなどをあらかじめダウンロードさせたい場合に使用します。

<link rel="prefetch" href="//example.com/next-page.html" as="document" crossorigin="use-credentials">
<link rel="prefetch" href="/library.js" as="script">

Prerender

Prefetch と同様に、次の遷移先にで使用する可能性のあるリソースをあらかじめダウンロードしますが、さらにレンダリング(DOMの構築やJavaScriptの実行)まで行うための定義です。

The prerender link relation type is used to identify a resource that might be required by the next navigation, and that the user agent SHOULD fetch and execute, such that the user agent can deliver a faster response once the resource is requested in the future. 2.4 Prerender

裏で別ページを開いておくようなイメージですが、Google Analyticsなどはカウントされないようです。

<link rel="prerender" href="//example.com/next-page.html">