← 中文资源

简体中文版本

如何使用连接预连接提示

用 preconnect、dns-prefetch 与 preload 提示削减请求延迟,使浏览器在需要前建立连接并获取资源。

阅读英文原文

引言

到第三方源的首次请求在任何响应字节到达前付 DNS 解析、TCP 连接与 TLS 协商。从多个源加载字体、脚本与图片的页面付该成本数次,且与渲染串行。预连接提示让页面告诉浏览器提前、并行建立那些连接,使成本在资源需要前付出。用得好,它们从关键路径削去建立延迟;用得草率,它们打开永不使用的连接。

建立成本

到新源的请求需要 DNS 查找、TCP 握手,对 HTTPS 还有 TLS 握手,全在请求发送前。冷连接上是若干往返,且若浏览器解析 HTML 找到资源前才知道该源,建立与资源发现串行。

提示把建立提前:浏览器在 HTML head 读提示并立即并行开始工作,到资源需要时连接就绪。节省的是建立延迟,移动网络上每源可达数百毫秒。

Preconnect、DNS-Prefetch 与 Preload

preconnect 做完整建立:DNS、TCP 与 TLS。它是最贵的提示、省最多,应保留给将很快使用且在关键路径上的源。dns-prefetch 只做 DNS 查找,更便宜,对可能使用的源有用。preload 获取特定资源使其需要时可得,减少发现延迟。

三者针对不同成本:DNS 解析、连接建立与资源获取。各用其用途:对关键第三方源 preconnect、对可能使用但非关键的 dns-prefetch、对关键渲染路径上的具体文件 preload。

预加载关键资源

preload 用于浏览器发现得晚但需要得早的资源:CSS 引用的字体、样式表引用的主图、另一脚本加载的脚本。Preload 在 head 声明它,使获取在解析时开始,早于引用文件被处理。

Preload 必须精确:as 属性,字体还需 crossorigin,使浏览器以正确方式获取并复用预加载资源而非再获取一次。属性错误的 preload 造成双重获取,比无 preload 更糟。测量预加载资源确实被复用。

选择提示什么

提示消耗资源,因此选择性使用。对关键路径且很快使用的源 preconnect;不要对可能使用的源 preconnect,因为未使用的 preconnect 浪费连接并与要紧的连接竞争。dns-prefetch 对可能的源足够便宜。

基于审计决定:哪些源出现在关键路径、哪些资源发现得晚但需要得早、哪些第三方源实际被用。盲目加提示会加与带宽和套接字竞争的建立工作。

测量效果

用浏览器自身工具测量:网络面板显示连接建立时间以及预加载资源是否被复用。省了建立时间的 preconnect 表现为该源更短的连接时间;有效的 preload 表现为无双重获取。

现场数据比实验室运行更要紧:节省在高延迟移动网络上最大,快实验室机器隐藏它。用 performance API 记录被提示源的建立时间并在现场比较被提示与未被提示的。

HTTP 头与 Early Hints

提示也可来自 HTTP 头,在服务端于 HTML 被解析前就知道资源时有用:带 rel=preconnect 或 rel=preload 的 Link 头。这对重定向请求或 HTML 体前的早期响应尤其有用。

Early Hints(103 响应)扩展这点:服务端在最终响应前发 Link 头,让浏览器在服务端仍在准备主响应时开始预连接与预加载。这是在 HTML 存在前提示的方式,在慢服务端响应上把建立从关键路径削去。

常见陷阱与小结

不要 preconnect 推测性源;未使用的 preconnect 浪费连接并争抢套接字。不要用错误属性 preload,那造成双重获取。不要提示太多源,那摊薄带宽。也不要在快实验室机器上评判效果;节省在高延迟真实网络上。

Preconnect、dns-prefetch 与 preload 通过告诉浏览器提前开始,把连接建立与资源发现移出关键路径。对关键第三方源 preconnect、对可能的 dns-prefetch、对晚发现的关键资源用精确属性 preload、并在现场测量节省。选择性使用时,提示削去跨源累积的建立延迟。

现场核验被提示的来源是否显示更短的连接建立时间。

代码示例

<!-- in the document head -->
<!-- full setup (DNS + TCP + TLS) for a known origin used soon -->
<link rel="preconnect" href="https://fonts.example.com" crossorigin>

<!-- DNS only, for an origin you will connect to but not immediately -->
<link rel="dns-prefetch" href="https://analytics.example.com">

<!-- fetch a critical resource the browser would only discover later -->
<link rel="preload" href="/fonts/inter.woff2" as="font" type="font/woff2" crossorigin>
# hint -> cost paid early
preconnect     -> DNS + TCP + TLS   (expensive; for critical origins)
dns-prefetch   -> DNS only           (cheap; for likely origins)
preload        -> fetch a resource   (reduces discovery delay)
prefetch       -> low-priority fetch for a future navigation
# pick by cost saved and how soon the origin or resource is needed
<!-- preload a font used by CSS, with the exact attributes -->
<link rel="preload" as="font" type="font/woff2"
      href="/fonts/inter.woff2" crossorigin>

<!-- preload a hero image referenced from a stylesheet -->
<link rel="preload" as="image" href="/hero.webp" fetchpriority="high">

<!-- wrong attrs => double fetch (worse than no preload); verify reuse in devtools -->
# decide from an audit
[ ] critical-path origins used soon  -> preconnect
[ ] likely but non-critical origins   -> dns-prefetch
[ ] late-discovered critical resources-> preload (exact as/crossorigin)
[ ] do NOT preconnect speculative origins (wastes a connection)
# hints compete for bandwidth and sockets; add deliberately
// Record connection timing for hinted origins in the field.
new PerformanceObserver((list) => {
  for (const e of list.getEntries()) {
    if (e.entryType === 'resource') {
      const setupMs = e.connectEnd - e.startTime; // connection setup time
      navigator.sendBeacon('/perf', JSON.stringify({ name: e.name, setupMs }));
    }
  }
}).observe({ type: 'resource', buffered: true });
// compare setup time for hinted vs unhinted origins on real networks
# Link headers carry the same hints from the server
HTTP/1.1 200 OK
Link: <https://fonts.example.com>; rel=preconnect; crossorigin
Link: </fonts/inter.woff2>; rel=preload; as=font; crossorigin

# Early Hints: send links BEFORE the final response
HTTP/1.1 103 Early Hints
Link: <https://cdn.example.com>; rel=preconnect
# browser starts setup while the server prepares the main response