Skip to content

前端的資源預加載 | Resource Hints

此文章是 FrontendMaster 上的 Advanced Web Development Quiz 課程筆記

問題:將以下詞彙與其定義配對

[1] dns-prefetch
[2] preconnect
[3] prefetch
[4] preload

[a] prioritizes fetching of critical resources needed for the current navigation
[b] perform domain name resolution in the background
[c] proactively performs DNS resolution and TCP/TLS handshake
[d] downloads resources that are likely to be needed in the future

資源預加載

這裡在討論的是以下四個情況的差別

html
<link src="..." rel="dns-prefetch" />
<link src="..." rel="preconnect" />
<link src="..." rel="prefetch" />
<link src="..." rel="preload" />

這些標籤通常會放在 <head> 裡面,當解析器讀到這個標籤後,會先去依據 rel 的值,先去執行相應的行為,用來提升第三方資源 (跨網域) 請求資源的效率

這又可以講回到請求資源時要做的一系列行為:

DNS 解析 ⭢ TCP 連線 ⭢ TLS 握手 ⭢ Request ⭢ Response

DNS 解析 - 將域名轉換為 IP 位址 TCP 連線 - 建立客戶端與伺服器之間的連線 TLS 握手 - (HTTPS) 確保雙方擁有相同憑證的安全連線 請求與回應

而上面四種不同的 rel 的值,分別能夠告訴瀏覽器在一開始就預先完成我們確定稍後要執行的行為,這樣子的資源預加載可以讓我們有更細緻化的網站速度優化的設定。

預設情況

在沒有設定任何預加載的情況下,預設行為就是瀏覽器解析到包含該網域的標籤或內容時才會去嘗試做請求

dns-prefetch

提前執行 DNS 解析

適合使用外部資源如 Google Fonts、Google APIs

  • 不要過度使用,會競爭頻寬
  • 低階裝置或網路不佳時可能導致其他資源等待
  • 瀏覽器有同時連線數量上限

preconnect

提前執行 DNS 解析 & TCP/TLS 握手

注意:過度使用 preconnect 會消耗資源

prefetch

在功能上等同於使用 fetch(),會把回應的內容存入瀏覽器快取,不過只有在瀏覽器閒置時才執行

適合情境:

  • 同站資源: 適合預取同站點的未來導航資源
  • 子資源預取: 適合預取當前頁面未使用但未來可能需要的子資源

preload

類似於 prefecth 的行為,但是會立刻去執行請求,並把資源儲存在快取中。確保資源在需要時立即可用,從而提升頁面載入效能。

適合情境:

  • 指定頁面中很快會用到的資源,會在瀏覽器渲染之前執行,不過如果是先請求 JS 並不會執行程式碼
  • CSS 背景圖片:preload scanner 無法看到 CSS 中的資源
  • 字型檔案:字型通常隱藏在 CSS 中,造成延遲
  • JavaScript

可以使用 as 屬性來指定資源類型,例如:<link rel="preload" href="style.css" as="style">

答案:

[1] dns-prefetch
[2] preconnect
[3] prefetch
[4] preload

[4][a] prioritizes fetching of critical resources needed for the current navigation
[1][b] perform domain name resolution in the background
[2][c] proactively performs DNS resolution and TCP/TLS handshake
[3][d] downloads resources that are likely to be needed in the future

參考

最後更新時間:

0 %
MIT Licensed | Copyright © 2025-present Wen-Hsiu's Blog