運用導覽預先載入功能加快服務工作處理程序的速度

預先載入導覽功能可讓您平行提出要求,克服 Service Worker 啟動時間的問題。

Jake Archibald
Jake Archibald

Browser Support

  • Chrome: 59.
  • Edge: 18.
  • Firefox: 99.
  • Safari: 15.4.

Source

摘要

問題

當你前往使用 Service Worker 處理擷取事件的網站時,瀏覽器會要求 Service Worker 提供回應。這包括啟動 Service Worker (如果尚未執行),以及調度擷取事件。

開機時間取決於裝置和條件。通常約為 50 毫秒。在行動裝置上則約為 250 毫秒。在極端情況下 (裝置速度緩慢、CPU 負載過重),可能會超過 500 毫秒。不過,由於 Service Worker 在事件之間會保持喚醒狀態一段時間 (由瀏覽器決定),因此只有在使用者從新分頁或其他網站前往您的網站時,才會偶爾發生這種延遲。

如果您是從快取回應,啟動時間就不是問題,因為略過網路的好處大於啟動延遲。但如果使用網路回應…

SW 啟動
導航要求

網路要求會因 Service Worker 啟動而延遲。

我們持續縮短啟動時間,包括在 V8 中使用程式碼快取、略過沒有擷取事件的 Service Worker、推測性啟動 Service Worker,以及其他最佳化措施。不過,啟動時間一律會大於零。

Facebook 提醒我們這個問題的影響,並要求提供平行執行導覽要求的方法:

SW 啟動
導航要求

預先載入導覽功能

預先載入導覽功能可讓您指定「當使用者提出 GET 導覽要求時,在 Service Worker 啟動時啟動網路要求」。

啟動延遲仍存在,但不會阻擋網路要求,因此使用者能更快取得內容。

以下是實際運作的影片,其中使用 while 迴圈刻意將 Service Worker 的啟動時間延遲 500 毫秒:

歡迎觀看示範影片。如要享有預先載入導覽的好處,您必須使用支援這項功能的瀏覽器。

啟用導覽預先載入功能

addEventListener('activate',> event = {
  event.waitUntil(async function() {
    // Feature-detect
    if (self.registration.navigationPreload) {
      // Enable navigation preloads!
      await self.registration.navigationPreload.enable();
    }
  }());
});

您隨時可以呼叫 navigationPreload.enable(),或使用 navigationPreload.disable() 停用。不過,由於 fetch 事件需要使用這項功能,因此最好在 Service Worker 的 activate 事件中啟用及停用這項功能。

使用預先載入的回覆

現在,瀏覽器會預先載入導覽,但您仍需使用回應:

addEventListener('fetch',> event = {
  event.respondWith(async function() {
    // Respond from the cache if we can
    const cachedResponse = await caches.match(event.request);
    if (cachedResponse) return cachedResponse;

    // Else, use the preloaded response, if it's there
    const response = await event.preloadResponse;
    if (response) return response;

    // Else try the network.
    return fetch(event.request);
  }());
});

event.preloadResponse 是一個承諾,在下列情況下會解析為回應:

  • 已啟用導覽預先載入功能。
  • 這項要求是 GET 要求。
  • 要求是導覽要求 (瀏覽器載入網頁 (包括 iframe) 時產生的要求)。

否則 event.preloadResponse 仍會存在,但會解析為 undefined。

如果網頁需要網路資料,最快的方法是在 Service Worker 中要求資料,並建立單一串流回應,其中包含快取和網路的部分。

假設我們要顯示一篇文章:

addEventListener('fetch',> event = {
  const url = new URL(event.request.url);
  const includeURL = new URL(url);
  includeURL.pathname += 'include';

  if (isArticleURL(url)) {
    event.respondWith(async function() {
      // We're going to build a single request from multiple parts.
      const parts = [
        // The top of the page.
        caches.match('/article-top.include'),
        // The primary content
        fetch(includeURL)
          // A fallback if the network >fails.
          .catch(() = caches.match('/article-offline.include')),
        // The bottom of the page
        caches.match('/article-bottom.include')
      ];

      // Merge them all together.
      const {done, response} = await mergeResponses(parts);

      // Wait until the stream is complete.
      event.waitUntil(done);

      // Return the merged response.
      return response;
    }());
  }
});

在上述程式碼中,mergeResponses 是合併各項要求串流的小函式。這表示我們可以在網路內容串流時,顯示快取的標頭。

這比「應用程式命令介面」模型更快,因為網路要求會與網頁要求一起提出,且內容可以串流,不需大幅修改。

不過,includeURL 的要求會因 Service Worker 的啟動時間而延遲。我們也可以使用導覽預先載入功能來修正這個問題,但在這種情況下,我們不想預先載入整個網頁,而是要預先載入包含的內容。

為支援這項功能,系統會在每次預先載入要求時傳送標頭:

Service-Worker-Navigation-Preload: true

伺服器可以利用這項資訊,為導覽預先載入要求傳送與一般導覽要求不同的內容。請記得新增 Vary: Service-Worker-Navigation-Preload 標頭,讓快取知道回應不同。

現在可以使用預先載入要求:

// Try to use the preload
const networkContent = Promise.resolve(event.preloadResponse)
  // Else do a normal fetch
  .then(r => r || fetch(includeURL))
  // A fallback if the network fails.
  .catch(() => caches.match('/article-offline.include'));

const parts = [
  caches.match('/article-top.include'),
  networkContent,
  caches.match('/article-bottom')
];

變更標頭

根據預設,Service-Worker-Navigation-Preload 標頭的值為 true,但您可以視需要設定:

navigator.serviceWorker.ready.then(registration => {
  return registration.navigationPreload.setHeaderValue(newValue);
}).then(() => {
  console.log('Done!';);
});

舉例來說,您可以將其設為本機快取的最後一則貼文 ID,這樣伺服器就只會傳回較新的資料。

取得狀態

您可以使用 getState 查詢導覽預先載入的狀態:

navigator.serviceWorker.ready.then(registration => {
  return registration.navigationPreload.getState();
}).then(state => {
  console.log(state.enabled); // boolean
  console.log(state.headerValue); // string
});

非常感謝 Matt Falkenhagen 和 Tsuyoshi Horo 協助開發這項功能,並協助撰寫本文。也感謝所有參與標準化工作的人員