通过导航预加载加快 Service Worker 的运行速度

借助导航预加载,您可以并行发出请求,从而缩短 Service Worker 启动时间。

Jake Archibald
Jake Archibald

Browser Support

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

Source

摘要

问题

当您前往使用 service worker 处理 fetch 事件的网站时,浏览器会向 service worker 请求响应。这包括启动服务工作器(如果尚未运行)和调度 fetch 事件。

启动时间取决于设备和条件。通常约为 50 毫秒。在移动设备上,延迟时间更接近 250 毫秒。在极端情况下(设备运行缓慢、CPU 处于紧急状态),此时间可能会超过 500 毫秒。不过,由于服务工作线程会在事件之间保持唤醒状态一段时间(由浏览器决定),因此您只会偶尔遇到这种延迟,例如当用户从新标签页或其他网站导航到您的网站时。

如果您从缓存中响应,启动时间就不是问题,因为跳过网络的好处大于启动延迟。但如果您使用网络进行回复…

SW 启动
导航请求

网络请求因 Service Worker 启动而延迟。

我们正在通过在 V8 中使用代码缓存跳过没有提取事件的服务工作线程推测性地启动服务工作线程和其他优化措施,继续缩短启动时间。不过,启动时间始终会大于零。

Facebook 向我们指出了此问题的影响,并要求提供一种并行执行导航请求的方法:

SW 启动
导航请求

导航预加载功能可解决此问题

导航预加载是一项功能,可让您指定“当用户发出 GET 导航请求时,在 Service Worker 启动时启动网络请求”。

启动延迟仍然存在,但不会阻塞网络请求,因此用户可以更快地获取内容。

以下视频展示了该功能在实际应用中的效果,其中使用 while 循环故意为服务工作线程设置了 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 事件需要使用它,因此最好在服务工作线程的 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 是一个会通过响应进行解析的 promise:

  • 已启用导航预加载。
  • 相应请求是 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 是一个用于合并每个请求的流的小函数。这意味着,我们可以在网络内容流式传输时显示缓存的标头。

这比“应用 shell”模型更快,因为网络请求是与网页请求一起发出的,并且内容可以流式传输,而无需重大黑客攻击

不过,对 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 为此功能做出的贡献,以及对本文的帮助。还要特别感谢参与标准化工作的所有人