【问题标题】:Vue PWA: Use ServiceWorker to cache remote media assets from array of URLsVue PWA:使用 ServiceWorker 缓存来自 URL 数组的远程媒体资产
【发布时间】:2020-03-11 15:23:13
【问题描述】:

我正在构建一个 PWA,如果用户愿意,我希望可以选择下载和缓存整个应用程序中使用的所有媒体资产。默认 PWA 行为仅在请求浏览应用程序时缓存资产。我需要提供按下按钮、下载资产、离线并使用整个应用程序并缓存所有资产的功能,而不必在在线时访问各种路线和视图。

对于上下文,当应用加载时,Vuex 从我的 API 中获取 JSON 内容,将其置于状态,然后保存到 IndexedDB。

如果用户单击“下载所有内容”按钮,我想解析 $store.state 中的 JSON,将 URL(图像、PDF 和 MP4)收集到一个数组中,并将该数组传递给 ServiceWorker 以故意缓存所有这些 URL 上的资产以供离线使用(不超过允许的原始存储限制)。

我正在使用 Vue CLI 和 Vue PWA 插件,所以我有 registerServiceWorker.js 文件并为生产生成了预缓存清单。

我在互联网上找到了关于这有点令人困惑的信息,我正在考虑使用https://developers.google.com/web/ilt/pwa/lab-caching-files-with-service-worker 概述的方法,但我不确定一些细节,也不确定如何以某种方式解决这个问题非常适合 Vue CLI 工作流程?

如果可能,您能否在回答中包含以下问题:

  1. 我使用的是 GenerateSW 还是 InjectManifest?

  2. 是否需要编写自己的 Service Worker,还是可以在 registerServiceWorker.js 中挂钩生命周期方法(registered()、cached()、updated())?

提前感谢您的帮助。

【问题讨论】:

  • 你解决过这个问题吗?我需要做同样的事情
  • @Brad 我实际上仍然面临这个问题。我想我有一个解决方案,但会尽快测试。我的计划是为我的内容遍历 JSON 数据,构建这些 URL 的数组,然后使用 Cache API 将这些 URL 添加到缓存中:web.dev/cache-api-quick-guide
  • 我们仍然没有答案,但是......我们可能会向 vue 使用的工作箱添加运行时缓存模式,如下所示:github.com/vuejs-templates/pwa/issues/…

标签: javascript vue.js caching service-worker progressive-web-apps


【解决方案1】:

我找到了一种在 Vue 3,Vue CLI PWA 应用程序上缓存远程文件的方法。

  1. 在根目录下设置vue.conig.js如下图

# vue.config.js
module.exports = {
  // ...other vue-cli plugin options...
  pwa: {
    name: "my-pwa-app",
    themeColor: "#624040",
    msTileColor: "#000000",
    // configure the workbox plugin
    workboxPluginMode: "InjectManifest",
    workboxOptions: {
      // swSrc is required in InjectManifest mode.
      swSrc: "service-worker.js", //path to your own service-worker file
      // ...other Workbox options...
    },
  },
};
  1. 使用下面的起始代码创建service-worker.js,添加缓存所需的其他功能

# service-worker.js
// workbox functions from the workbox CDN (version 4.3.1) 
// Vue 3 PWA automatically adds the CDN
const { precacheAndRoute } = workbox.precaching;
const { registerRoute } = workbox.routing;
const { CacheFirst, StaleWhileRevalidate } = workbox.strategies;
const { Plugin: ExpirationPlugin } = workbox.expiration;
const { Plugin: CacheableResponsePlugin } = workbox.cacheableResponse;

workbox.core.setCacheNameDetails({ prefix: "appname" });

self.addEventListener("message", (event) => {
  if (event.data && event.data.type === "SKIP_WAITING") {
    self.skipWaiting();
  }
});

/**
 * The workboxSW.precacheAndRoute() method efficiently caches and responds to
 * requests for URLs in the manifest.
 */
self.__precacheManifest = [].concat(self.__precacheManifest || []);
precacheAndRoute(self.__precacheManifest, {});

// cache image and render from the cache if it exists or go t the network
registerRoute(
  ({ request }) => request.destination === "image",
  new CacheFirst({
    cacheName: "images",
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
      new ExpirationPlugin({
        maxEntries: 60,
        maxAgeSeconds: 2 * 24 * 60 * 60, // cache the images for only 2 Days
      }),
    ],
  })
);

// cache API response and serve from cache if exists or go to the network 
registerRoute(
  ({ url }) => url.pathname.startsWith("https://dog.ceo/api/"),
  new StaleWhileRevalidate()
);

VueJs 采用 service-worker.js 并添加其导入以预缓存 /dist 文件夹中的文件

  • 可以找到 Workbox 的文档here
  • 关于工作箱 4.3.1 的注释我发现很有用 here

【讨论】:

    猜你喜欢
    • 2019-09-26
    • 1970-01-01
    • 2013-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多