缓存远程 HTTP 资产

cache remote HTTP asset

我希望使用 Workbox 来缓存本地和远程图像资源。目前是否支持,如果支持如何?

基本上我想要以下功能:

workboxBuild.injectManifest({
    swSrc: 'app/sw.js',
    swDest: 'build/sw.js',
    globDirectory: 'build',
    globPatterns: [
      '*.css',
      'index.html',
      'app.js',
      'http://remote/image.jpg'
    ],

如果我手动将远程 HTTP 资产添加到生成的服务工作者文件中,那是可行的(见下文),但我希望生成该服务工作者文件而无需手动编辑它。

importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.4.1/workbox-sw.js');

if (workbox) {
  console.log(`Yay! Workbox is loaded `);
  workbox.precaching.precacheAndRoute([
  {
    "url": "app.css",
    "revision": "f8d6a881fb9d586ef6fd676209e1613b"
  },
  {
    "url": "index.html",
    "revision": "ce6238d5b3c1e4e559349549c9bd30aa"
  },
  {
    "url": "app.js",
    "revision": "4357dbdbcc80dcfbe1f8198ac0313009"
  },
  {
    "url": "http://remote/image.jpg"
  }
]);

} else {
  console.log(`Boo! Workbox didn't load `);
}

不支持预缓存远程资产。这不太可能改变。作为构建过程的一部分,Workbox 需要在部署之前获取每个资源的 "snapshot",以便填充和更新其缓存,同时以缓存优先的方式为它们提供服务。虽然理论上您可以在构建过程中对远程资源发出 HTTP 请求,以获取它的版本控制信息,但不能保证该远程资源不会在您的第一个部署周期之外重新部署-党的资产。这可能会让您陷入这样一种情况,即 Workbox 认为它拥有最新版本的 http://example.com/image.jpg,并且从不获取它的最新更新。

通往 handle third-party, remote assets is to use runtime routing along with a caching strategy 的方式为您提供您认为适合特定类型资产的新鲜度保证。如果您希望在安装 Service Worker 后立即自动缓存给定资产,您可以添加自己的 install 处理程序,它将 "prime" 运行时缓存。

这看起来像:

// Workbox will continue to precache and keep
// the local assets it knows about up to date.
workbox.precaching.precacheAndRoute([...]);

const cacheName = 'image-cache';

// Make sure that these URLs support CORS!
// Otherwise, the cache.addAll() call will fail,
// and you'll have to explicitly call cache.put()
// for each resource.
const thirdPartyUrls = [
  'https://example.com/image.jpg',
  // Any other URLs.
];

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(cacheName)
      .then((cache) => cache.addAll(thirdPartyUrls))
  );
});

workbox.routing.registerRoute(
  new RegExp('^https://example.com/'),
  // Use whichever strategy you want.
  workbox.strategies.staleWhileRevalidate({
    cacheName,
    // Use whatever plugins you want.
    plugins: [...],
  }),
);