推測載入(Speculative Loading)如何提高WordPress網站的頁面速度

推測載入(Speculative Loading)

如今,網頁中充斥著旨在增強使用者體驗的圖片、視訊和互動元素。然而,這些元素會拖慢網頁的載入時間。

隨著技術的進步,有一個目標始終不變:效能。每個人都希望自己的網頁能以閃電般的速度載入

讓網頁載入速度更快的一種方法是在使用者瀏覽網頁之前進行預渲染或預獲取。

預渲染簡史

2011 年,Chromium 團隊通過 <link ... > 標籤為 Chrome 瀏覽器引入了早期的預渲染功能。

這樣,開發人員就可以向瀏覽器提示使用者下一步可能訪問的頁面。然後,瀏覽器會在後臺靜默地獲取並呈現這些頁面,從而大大縮短了使用者瀏覽這些頁面時的載入時間。

儘管好處多多,但這種早期的預渲染功能會佔用大量頻寬和 CPU 資源,而且如果使用者不訪問預渲染的頁面,還可能導致隱私問題。此外,你還必須手動選擇要預演的連結,這並不總是有效或可行的。

為了解決其中的一些問題,Chrome 瀏覽器放棄了使用連結 rel=prerender 提示進行預渲染,轉而使用 NoState Prefetch 方法,即在不執行 JavaScript 或其他可能侵犯隱私的操作的情況下獲取頁面資源。

NoState Prefetch 方法改善了資源載入,但無法像完全預渲染那樣提供即時頁面載入。

推測載入 API

推測載入 API(Speculation Rules API)是一種新的試驗性 JSON 定義 API,可在導航到 URL 之前推測性地預載入 URL,從而加快呈現時間並改善使用者體驗。

通過該 API,開發人員可在指令碼 type="speculationrules" 中配置以 JSON 格式定義的結構規則,瀏覽器可使用該指令碼決定哪些 URL 應進行預渲染。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<script type="speculationrules">
{
"prerender": [
{
"source": "list",
"urls": ["firstpage.html", "secondpage.html"]
}
]
}
</script>
<script type="speculationrules"> { "prerender": [ { "source": "list", "urls": ["firstpage.html", "secondpage.html"] } ] } </script>
<script type="speculationrules">
{
"prerender": [
{
"source": "list",
"urls": ["firstpage.html", "secondpage.html"]
}
]
}
</script>

在預取時也是如此,預取通常是預渲染的第一步:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<script type="speculationrules">
{
"prefetch": [
{
"urls": ["firstpage.html", "secondpage.html"]
}
]
}
</script>
<script type="speculationrules"> { "prefetch": [ { "urls": ["firstpage.html", "secondpage.html"] } ] } </script>
<script type="speculationrules">
{
"prefetch": [
{
"urls": ["firstpage.html", "secondpage.html"]
}
]
}
</script>

上面的程式碼片段展示了 Speculation Rules API 如何通過指定要預取或預渲染的 URL 列表來工作。

最近,Google 宣佈對 Speculation Rules API 進行新的改進,現在可以選擇使用文件規則自動查詢連結。其工作原理是根據 where 條件從文件中獲取 URL。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<script type="speculationrules">
{
"prerender": [
{
"source": "document",
"where": {
"and": [
{
"href_matches": "/*"
},
{
"not": {
"href_matches": [
"/wp-login.php",
"/wp-admin/*"
]
}
}
]
},
"eagerness": "moderate"
}
]
}
</script>
<script type="speculationrules"> { "prerender": [ { "source": "document", "where": { "and": [ { "href_matches": "/*" }, { "not": { "href_matches": [ "/wp-login.php", "/wp-admin/*" ] } } ] }, "eagerness": "moderate" } ] } </script>
<script type="speculationrules">
{
"prerender": [
{
"source": "document",
"where": {
"and": [
{
"href_matches": "/*"
},
{
"not": {
"href_matches": [
"/wp-login.php",
"/wp-admin/*"
]
}
}
]
},
"eagerness": "moderate"
}
]
}
</script>

在此程式碼段中,除了那些指向 WordPress 登入和管理頁面的 URL 外,頁面上的所有 URL 都會被視為預渲染物件。您還可以指定 eagerness 程度 – eager(立即)、moderate(懸停 200 毫秒後)和conservative(滑鼠或觸控時)。

CSS 選擇器還可以替代或與 href 匹配器一起用於查詢當前頁面上的連結:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<script type="speculationrules">
{
"prerender": [{
"source": "document",
"where": {
"and": [
{ "selector_matches": ".prerender" },
{ "not": {"selector_matches": ".do-not-prerender"}}
]
},
"eagerness": "moderate"
}]
}
</script>
<script type="speculationrules"> { "prerender": [{ "source": "document", "where": { "and": [ { "selector_matches": ".prerender" }, { "not": {"selector_matches": ".do-not-prerender"}} ] }, "eagerness": "moderate" }] } </script>
<script type="speculationrules">
{
"prerender": [{
"source": "document",
"where": {
"and": [
{ "selector_matches": ".prerender" },
{ "not": {"selector_matches": ".do-not-prerender"}}
]
},
"eagerness": "moderate"
}]
}
</script>

使用 Speculation Rules API 時,可以在檢查頁面時使用 Chrome 瀏覽器應用選項卡中的推測載入後臺服務進行檢查。

推測載入後臺服務

使用 Chrome 瀏覽器應用選項卡中的推測載入後臺服務檢查 Speculation Rules API。

還有更多內容,我們將在除錯部分進行探討。

瀏覽器支援

從特定版本開始,基於 Chromium 的現代瀏覽器(包括 Chrome 瀏覽器和 Edge)都支援 Speculation Rules API

瀏覽器支援 Speculation Rules API

瀏覽器支援 Speculation Rules API(來源:Mozilla)。

這確保了受支援瀏覽器的使用者可以從更快的載入時間中受益,而其他瀏覽器的使用者則不會受到任何負面影響,因為 API 是一種漸進式增強工具。

WordPress 外掛 Speculative Loading

為了在 WordPress 中享受 Speculation Rules API 的優勢,WordPress 效能團隊(包括來自 Google 的開發人員)最近釋出了 Speculative Loading 外掛。該外掛可以對頁面上鍊接的前端 URL 進行 speculative loading。

到目前為止,由於 API 仍處於早期階段,該外掛的採用率較低,但也獲得了一些好評。

Speculative Loading 外掛的評價

WordPress 社羣對 Speculative Loading 外掛的評價。

預設情況下,該外掛會在使用者將滑鼠懸停在相關連結上時預渲染 WordPress 前端 URL。可以通過設定 > 閱讀下的 “Speculative Loading” 部分對此進行自定義。

自定義 Speculative Loading 外掛

在 WordPress 管理設定中自定義 Speculative Loading 外掛。

這意味著頁面上鍊接的任何 URL 都會以 moderate 的 eagerness 配置進行預渲染,通常會在懸停在連結上時觸發。因此,啟用外掛後您不需要做任何事情,它就會自動執行。

例如,如果你已經在 WordPress 網站上安裝了 Speculative Loading 外掛。使用 Chrome 瀏覽器開發工具檢查網站,然後點選元素選項卡。向下滾動時,您會發現一個 type="speculationrules" 的指令碼已為您新增了各種推測規則。

auto-speculative-rules

檢查 WordPress 網站,檢視 Speculative Loading 外掛自動新增的推測規則。

它使用 Regex 來指定應該預渲染的連結,指定不預渲染的連結,並設定渴望程度。下文將詳細解釋這些規則。

防止過度使用的限制

Chrome 瀏覽器為防止過度使用 API 設定了限制:

Eagerness 預取 預渲染
immediate/eager 50 10
moderate/conservative 2 (FIFO) 2 (FIFO)

它們通過基於緊迫性和使用者互動的各種設定來防止過度使用。

  • immediate 和 eager — – 它們不依賴於使用者操作,因此具有更高的限制。它們允許通過刪除舊的猜測來動態調整容量。
  • moderate 和 conservative — 與此相反,這些設定由使用者觸發,遵循先進先出(FIFO)原則,上限為 2,用新的推測替換最舊的推測,以節省記憶體。

當 eagerness 設定為 moderate 時,先進先出上限為 2

當 eagerness 設定為 moderate 時,先進先出上限為 2。

防止某些 URL 預取和預渲染

需要注意的是,WP-admin 路由預設情況下不包括在預呈現和預取中。作為 WordPress 開發人員,您可以自行決定優先處理哪些路由。

您可以使用 plsr_speculation_rules_href_exclude_paths 過濾器自定義推測預載哪類 URL 的規則。

以下程式碼示例可確保 https://wordpresssite.com/cart/https://wordpresssite.com/cart/book/ 等 URL 不被預取和預渲染:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
add_filter(
'plsr_speculation_rules_href_exclude_paths',
function ( $exclude_paths ) {
$exclude_paths[] = '/cart/*';
return $exclude_paths;
}
);
<?php add_filter( 'plsr_speculation_rules_href_exclude_paths', function ( $exclude_paths ) { $exclude_paths[] = '/cart/*'; return $exclude_paths; } );
<?php
add_filter(
'plsr_speculation_rules_href_exclude_paths',
function ( $exclude_paths ) {
$exclude_paths[] = '/cart/*';
return $exclude_paths;
}
);

有時,您可能希望將某個 URL 排除在預渲染之外,並允許對其進行預取。例如,使用客戶端 JavaScript 更新使用者狀態的頁面可能不應預演,但預取是合理的。

為此,plsr_speculation_rules_href_exclude_paths 過濾器會接收當前模式(prefetch 或 prerender),以提供條件排除。

例如,讓我們確保像 https://wordpresssite.com/products/ 這樣的 URL 不能被預渲染,同時仍允許對其進行預取。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
add_filter(
'plsr_speculation_rules_href_exclude_paths',
function ( array $exclude_paths, string $mode ): array {
if ( 'prerender' === $mode ) {
$exclude_paths[] = '/products/*';
}
return $exclude_paths;
}
);
<?php add_filter( 'plsr_speculation_rules_href_exclude_paths', function ( array $exclude_paths, string $mode ): array { if ( 'prerender' === $mode ) { $exclude_paths[] = '/products/*'; } return $exclude_paths; } );
<?php
add_filter(
'plsr_speculation_rules_href_exclude_paths',
function ( array $exclude_paths, string $mode ): array {
if ( 'prerender' === $mode ) {
$exclude_paths[] = '/products/*';
}
return $exclude_paths;
}
);

除錯 WordPress 網站的推測規則

由於預渲染頁面是在一個單獨的渲染器中渲染的,就像一個隱藏的背景標籤頁,啟用後會取代當前標籤頁,因此除錯推測規則可能很棘手。Chrome 瀏覽器團隊在 DevTools 方面做了大量工作,讓你可以使用它們進行除錯。

在 Chrome DevTools 中,導航至應用選項卡,然後向下滾動至推測載入選項卡。這將為開發人員提供有關 Speculation、預渲染 URL、失敗 URL 等的詳細資訊。

除錯推測規則

在 Chrome 瀏覽器開發工具中除錯推測規則。

在此,您可以看到頁面上的五個連結可以根據符合推測規則 JSON 中設定的規則的 URL 進行預渲染,如下所示。請注意,您不需要列出所有 URL;文件規則允許瀏覽器從頁面上的相同來源連結中獲取這些 URL。

被預取或預渲染

Chrome Devtool 會顯示網站各種連結的相關資訊,讓你知道它們何時被預取或預渲染。

一些連結的狀態顯示為“未觸發”–這些連結的預渲染過程尚未開始。不過,當我們將滑鼠懸停在頁面上的連結上時,就會看到每個 URL 的預渲染狀態都在發生變化。

請記住,Chrome 瀏覽器對預渲染設定了限制,包括 moderate 急切最多隻能預渲染兩次,因此在將滑鼠懸停在第三個連結上後,我們會看到該 URL 的失敗原因:

先進先出

懸停兩個連結後,先進先出就會生效。

還可以通過右上角的下拉選單或在面板上部選擇 URL 並選擇“檢查”來切換 DevTools 面板使用的渲染器:

檢查預渲染頁面

使用 Chrome DevTools 檢查預渲染頁面。

該下拉選單(和所選的值)在所有其他面板上共享,如網路面板,在該面板上可以看到正在請求的頁面是預渲染的頁面:

已預渲染的檔案

預渲染頁面的網路選項卡,顯示已預渲染的檔案。

在“元素”面板上可以看到頁面內容:

預渲染頁面的 HTML 內容

元素選項卡顯示預渲染頁面的 HTML 內容。

與除錯預編輯頁面一樣,您也可以預取頁面。對於推測載入外掛,請確保選擇 Prefetch 作為 Speculation Mode

將“Prerender”切換為“Prefetch”

使用推測載入設定將“Prerender”切換為“Prefetch”。

現在,當您使用 DevTools 檢查頁面並導航到推測載入選項卡時,各種 URL 的 Action 都將變為 Prefetch,規則也將隨之改變。

訪問每個預取連結的狀態

可以通過 Chrome 瀏覽器開發工具訪問每個預取連結的狀態。

懸停連結後導航到網路選項卡時,從 Type 列可以看到,預取資源顯示在最後。這些資源是以最低優先順序獲取的,因為它們是用於未來導航的,而 Chrome 瀏覽器會優先獲取當前頁面的資源。

懸停連結時,網路選項卡會顯示預取頁面

懸停連結時,網路選項卡會顯示預取頁面。

效能比較

到目前為止,您已經瞭解了 Speculative Loading 外掛的作用和工作原理。理論已經講得夠多了;讓我們來比較一下同一伺服器上兩個相同網站的效能。

為此,我在同一個資料中心(愛荷華州(美國中部),使用谷歌的 C3D 虛擬機器提升)建立了兩個 WordPress 網站,兩個網站都沒有安裝任何其他外掛。

比較使用和未使用 Speculative Loading 外掛的網站

我們建立了兩個網站,以比較使用和未使用 Speculative Loading 外掛的網站。

“Bare-site”不帶外掛,而“Speculative-site”則在 WordPress 儀表盤上安裝並啟用了“Speculative Loading”外掛。

重要的是要知道,Speculative Rules API 只能提高載入下一頁所需的時間,而不能根據 Lighthouse 等一般網站效能工具來判斷。

我們可以通過從兩個網站的特定內部連結載入頁面來測試頁面速度,並在檢查網站時使用 Chrome DevTool 的 Network 選項卡檢視載入時間和其他資訊。

對於“Bare-site”,你會發現它的載入時間更長,因為整個載入過程都是在移動中進行的,而 DOM 內容才剛剛載入:

未預渲染的網站要載入 DOM 內容和其他資訊

未預渲染的網站由於要載入 DOM 內容和其他資訊,因此需要更長的時間。

但對於“Speculative-site”,DOM 內容已通過 Speculative API 載入並快取。

預渲染的網站不會再次載入 DOM 內容

已使用 Speculative Loading 外掛預渲染的網站不會再次載入 DOM 內容。

兩個網站之間的差異可能看起來很小。在本例中,差異約為 0.22 秒,但對於內容較多的大型網站來說,差異就開始明顯了。

Speculation Rules API 對跟蹤程式碼的影響

分析對於通過頁面瀏覽和事件跟蹤網站使用情況以及通過真實使用者監控(RUM)評估效能至關重要。要知道,預渲染可能會影響分析。

例如,使用 Speculation Rules API 可能需要額外的程式碼,以便僅在實際訪問預渲染頁面時啟用分析功能。雖然 Google Analytics、Google Publisher Tag (GPT) 和 Google AdSense 會延遲跟蹤,直到頁面啟用為止,但並非所有提供商都預設這樣做。

為了解決這個問題,可以設定一個 Promise,只有在頁面啟用時才初始化分析:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// Promise to activate analytics on page activation for prerendered pages
const whenActivated = new Promise((resolve) => {
if (document.prerendering) {
document.addEventListener('prerenderingchange', resolve);
} else {
resolve();
}
});
async function initAnalytics() {
await whenActivated;
// Initialize analytics
}
initAnalytics();
// Promise to activate analytics on page activation for prerendered pages const whenActivated = new Promise((resolve) => { if (document.prerendering) { document.addEventListener('prerenderingchange', resolve); } else { resolve(); } }); async function initAnalytics() { await whenActivated; // Initialize analytics } initAnalytics();
// Promise to activate analytics on page activation for prerendered pages
const whenActivated = new Promise((resolve) => {
if (document.prerendering) {
document.addEventListener('prerenderingchange', resolve);
} else {
resolve();
}
});
async function initAnalytics() {
await whenActivated;
// Initialize analytics
}
initAnalytics();

小結

本文介紹了什麼是 Speculative Rules API、它如何工作以及如何在 WordPress 網站上使用它。它仍是一項試驗性功能,但已逐漸被廣泛採用。

推測規則仍然僅限於同一標籤頁中的頁面,但開發人員正在努力減少這些限制。

評論留言