代码之家  ›  专栏  ›  技术社区  ›  Tamas

缓存远程HTTP资产

  •  6
  • Tamas  · 技术社区  · 6 年前

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

    基本上我想拥有以下功能:

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

    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 😬`);
    }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Jeff Posnick    6 年前

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

    通往 handle third-party ,远程资源将使用 runtime routing 以及 caching 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: [...],
      }),
    );