← 中文资源

简体中文版本

预连接与 DNS 预取提示

预连接与 dns-prefetch 提前预热即将使用来源的连接,削减首次真实请求前的 DNS、TCP 与 TLS 延迟,但需要节制使用。

阅读英文原文

概念概述

预连接与 DNS 预取提示(Preconnect and DNS-Prefetch Hints)指的是:预连接与 dns-prefetch 提前预热即将使用来源的连接,削减首次真实请求前的 DNS、TCP 与 TLS 延迟,但需要节制使用。

从更严格的定义看,These resource hints ask the browser to begin name resolution, and optionally the full connection setup, to an origin in advance of the request that will actually use it. 该概念在工程实践中的价值,在于它能帮助团队用统一的语言描述一个具体的质量属性或设计约束,从而在评审与协作中减少歧义。

为什么需要它

They are applied to critical third-party origins such as font, analytics, or API hosts identified during performance profiling. 它与 Fetch Priority Signals、Speculative Parsing and Preload Scanner、Render-Blocking Resources 等概念经常一起出现,用于解决相近的工程问题。理解它的适用场景,有助于在多种备选方案之间做出有依据的取舍,而不是凭直觉选择技术方案。

常见误解

  • preconnect is free and can be added for every origin
  • dns-prefetch already performs the TLS handshake

需要避免的反模式

  • adding preconnect for dozens of origins indiscriminately
  • combining preconnect with an attribute that blocks rendering

实践要点

  1. A dns-prefetch hint resolves the hostname, while preconnect goes further and opens TCP and TLS, so the latter saves more time but consumes a socket and browser resources.
  2. Browsers cap the number of concurrent speculative connections, so overusing preconnect can starve real requests; reserve it for a small set of known-critical origins.
  3. Combine hints with a crossorigin attribute when the connection needs a separate credential context, otherwise the warmed socket will not be reused by the actual fetch.

参考来源

https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel/preconnect