Service Worker 将来自 API 调用的文件添加到预缓存 [英] Service worker add files from API call to precache

查看:80
本文介绍了Service Worker 将来自 API 调用的文件添加到预缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

启用我的应用离线运行.在安装过程中,Service Worker 应该:

To enable my app running offline. During installation the service worker should:

  1. 从异步 API 中获取 URL 列表
  2. 重新格式化响应
  3. 将响应中的所有 URL 添加到预缓存

对于这项任务,我将 Googles Workbox 与 Webpack 结合使用.

For this task I use Googles Workbox in combination with Webpack.

问题:虽然 service worker 成功缓存了所有 Webpack 资产(这告诉我工作箱基本上做了它应该做的事情),但它不会等待异步 API 调用来缓存额外的远程资产.它们只是被忽略,既不缓存也不在网络中获取.

The problem: While the service worker successfully caches all the Webpack assets (which tells me that the workbox basically does what it should), it does not wait for the async API call to cache the additional remote assets. They are simply ignored and neither cached nor ever fetched in the network.

这是我的服务工作者代码:

Here is my service worker code:

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

workbox.skipWaiting();
workbox.clientsClaim();

self.addEventListener('install', (event) => {
  const precacheController = new workbox.precaching.PrecacheController();
  const preInstallUrl = 'https://www.myapiurl/Assets';
  event.waitUntil(fetch(preInstallUrl)
    .then(response => response.json()
      .then((Assets) => {
        Object.keys(Assets.data.Assets).forEach((key) => {
          precacheController.addToCacheList([Assets.data.Assets[key]]);
        });
      })));
});
self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.suppressWarnings();
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});

workbox.routing.registerRoute(/^.*\.(jpg|JPG|gif|GIF|png|PNG|eot|woff(2)?|ttf|svg)$/, workbox.strategies.cacheFirst({ cacheName: 'image-cache', plugins: [new workbox.cacheableResponse.Plugin({ statuses: [0, 200] }), new workbox.expiration.Plugin({ maxEntries: 600 })] }), 'GET');

这是我对工作箱的 webpack 配置:

And this is my webpack configuration for the workbox:

new InjectManifest({
  swDest: 'sw.js',
  swSrc: './src/sw.js',
  globPatterns: ['dist/*.{js,png,html,css,gif,GIF,PNG,JPG,jpeg,woff,woff2,ttf,svg,eot}'],
  maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,
}),

推荐答案

我意识到了我的错误.我希望这也能帮助其他人.问题是我没有手动调用 precacheController.install() .虽然此函数将自动执行,但它不会等待异步插入的其他预缓存文件.这就是为什么需要在所有预缓存发生后调用该函数的原因.这是工作代码:

I realised my mistake. I hope this helps others as well. The problem was that I did not call precacheController.install() manually. While this function will be executed automatically it will not wait for additional precache files that are inserted asynchronously. This is why the function needs to be called after all the precaching happened. Here is the working code:

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

workbox.skipWaiting();
workbox.clientsClaim();

const precacheController = new workbox.precaching.PrecacheController();

// Hook into install event
self.addEventListener('install', (event) => {
  // Get API URL passed as query parameter to service worker
  const preInstallUrl = new URL(location).searchParams.get('preInstallUrl');

  // Fetch precaching URLs and attach them to the cache list
  const assetsLoaded = fetch(preInstallUrl)
    .then(response => response.json())
    .then((values) => {
      Object.keys(values.data.Assets).forEach((key) => {
        precacheController.addToCacheList([values.data.Assets[key]]);
      });
    })
    .then(() => {
      // After all assets are added install them
      precacheController.install();
    });
  event.waitUntil(assetsLoaded);
});

self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.suppressWarnings();
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});

workbox.routing.registerRoute(/^.*\.(jpg|JPG|gif|GIF|png|PNG|eot|woff(2)?|ttf|svg)$/, workbox.strategies.cacheFirst({ cacheName: 'image-cache', plugins: [new workbox.cacheableResponse.Plugin({ statuses: [0, 200] }), new workbox.expiration.Plugin({ maxEntries: 600 })] }), 'GET');

这篇关于Service Worker 将来自 API 调用的文件添加到预缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆