缓存远程HTTP资产

问题描述 投票:6回答:1

我希望使用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
1个回答
0
投票

不支持预先缓存的远程资产。这不太可能改变。作为构建过程的一部分,Workbox需要在部署之前获取每个资源的“快照”,以便填充和更新其缓存,同时为缓存提供缓存。虽然理论上可以在构建过程中为远程资源发出HTTP请求,但为了获取它的版本信息,无法保证在第一次部署周期之外不会重新部署该远程资源。 - 资产。这可能会让您处于Workbox认为它具有最新版本的http://example.com/image.jpg的情况,并且永远不会获取最近的更新。

通往handle third-party,远程资产的方法是使用runtime routingcaching strategy,为您提供您认为适合特定类型资产的新鲜度保证。如果您希望在安装服务工作者后立即自动缓存给定资产,则可以添加自己的install处理程序,该处理程序将为您“启动”运行时缓存。

这看起来像是这样的:

// 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: [...],
  }),
);
© www.soinside.com 2019 - 2024. All rights reserved.