Angular service-worker 正在预取视频文件

Angular service-worker prefetching video file

当页面上嵌入视频时,service worker 预取 整个视频,这会导致性能问题。在我的 ngsw-config.json 中,只有本地文件的配置,但视频位于 /sites/default/files/video/[= 下的不同子域中26=]文件夹结构。

如何从预取中排除所有文件请求?我只想预取 files/urls,我在 ngsw-config.json.

中进行了描述
<video width="320" height="240" controls>
  <source src="https://some.external.url.com/sites/default/files/video/video.mp4" type="video/mp4">
</video>

ngsw-config.json

  "$schema": "./node_modules/@angular/service-worker/config/schema.json",
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "updateMode": "prefetch",
      "resources": {
        "files": [
          "/favicon.ico",
          "/index.html",
          "/*.css",
          "/*.js"
        ],
        "urls": [
          "https://fonts.googleapis.com/icon?family=Material+Icons",
          "https://fonts.gstatic.com/s/materialicons/v50/flUhRq6tzZclQEJ-Vdg-IuiaDsNcIhQ8tQ.woff2"
        ]
      }
    }, {
      "name": "assets",
      "installMode": "prefetch",
      "updateMode": "prefetch",
      "resources": {
        "files": [
          "/assets/**",
          "/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
        ]
      }
    }
  ]
}

您可以为该外部设置 "lazy" installMode URL。

我可以通过扩展默认的 ngsw-worker.js 文件来解决这个问题。

  1. 我将 ngws-worker.js 从构建复制到项目 src 文件夹
  2. 已将其重命名为 custom-ngsw-worker.js
  3. 将 .mp4 正则表达式匹配添加到 onFetch(event) 方法
  4. 将此 .js 文件添加到 angular.json 资产
  5. 注册在app.module.ts而不是原来的ngsw-worker.js

app.module.ts

imports: [
...
ServiceWorkerModule.register('custom-ngsw-worker.js', { enabled: true, registrationStrategy: 'registerImmediately' }),
...
]

自定义-ngsw-worker.js

onFetch(event) {

...

// Skip video files
if (req.url.match('^.*(\.mp4).*$')
) {
  return;
}

...

这样它会忽略所有 .mp4 文件并且不会缓存它们。如果有更好的解决方案请告诉我。