我应该使用工作箱运行时缓存 staleWhileRevalidate 来缓存 gtm.js 吗?

Should i use workbox runtime caching staleWhileRevalidate to cache gtm.js?

我在我的 next.js 应用程序中使用 GTM,我正在使用 next-offline,它在内部使用 workbox-webpack-plugin 来提供离线支持,使用运行时缓存是个好主意吗staleWhileRevalidate 缓存策略 gtm.js ?

我的应用程序离线工作,它离线保存分析并通过导入此脚本在重新在线时发送它们:

// Initialize offline google analytics which will store failed analytics requests and try again later when connection is back
// it will also cache the analytics.js library
workbox.googleAnalytics.initialize({
  // using a custom dimension(cd1) to track online vs. offline interactions
  parameterOverrides: {
    cd1: "offline"
  },
  // Using a custom metric to track time requests spent in the queue
  hitFilter: params => {
    const queueTimeInSeconds = Math.round(params.get("qt") / 1000);
    params.set("cm1", queueTimeInSeconds);
  }
});

假设第二次访问的用户打开了我的主页,我使用运行时缓存和 networkFirst 策略来缓存 html,因此如果用户在完全离线时再次访问我的主页,他将获得完全可用的应用程序,尤其是我使用相同的 networkFirst 运行时缓存策略来缓存 api 请求,但是当完全离线时,获取 gtm.js 的请求将 return 404 并且分析将不起作用脱机,因为 gtm.js 不会启动请求以获取 analytics.js,这将从工作箱缓存中提供。我的想法是使用 staleWhileRevalidate 策略来缓存 gtm.js,这样即使用户在离线模式下打开应用程序,离线分析也能正常工作,如果他回到在线状态,这些分析将由 workbox 重新发送。

这是个好主意吗?它会按预期工作还是我遗漏了什么?

我不熟悉 gtm.js,但是 workbox-google-analytics will automatically 创建适当的运行时缓存路由来处理对 analytics.jsgtag.js 脚本给你:

Workbox Google Analytics does exactly this. It also also adds fetch handlers to cache the analytics.js and gtag.js scripts, so they can also be run offline. Lastly, when failed requests are retried Workbox Google Analytics also automatically sets (or updates) the qt in the request payload to ensure timestamps in Google Analytics reflect the time of the original user interaction.

听起来 gtm.js 是从与 gtag.js 不同的 URL 加载的,并且其集合 ping 的语法可能不同,因此工作箱中的 filing a feature request GitHub 请求 gtm.js 支持的回购听起来是你最好的选择。