在Angular Service worker中缓存index.html [英] Caching of index.html in Angular Service worker

查看:257
本文介绍了在Angular Service worker中缓存index.html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次我使用我的角度项目对index.html进行任何更改时,Serviceworker都不会更新,并且始终在index.html上提供旧的缓存版本。我该如何解决(服务器端和浏览器也没有缓存)

Everytime I make any change to the index.html with my angular project, Serviceworker never gets updated and always serves the old cached version on index.html. How do I fix this (Also, there is no caching at the server end as well as browser)

这是我的ngsw-config文件

Here is my ngsw-config file

{
  "index": "/index.html",
  "assetGroups": [{
    "name": "app",
    "installMode": "prefetch",
    "resources": {
      "files": [
        "/favicon.ico",
        "/index.html",
        "/manifest.json"
      ],
      "versionedFiles": [
        "/*.bundle.css",
        "/*.bundle.js",
        "/*.chunk.js"
      ]
    }
  }, {
    "name": "assets",
    "installMode": "lazy",
    "updateMode": "prefetch",
    "resources": {
      "files": [
        "/assets/**"
      ]
    }
  }]
}

我对请求的响应标头:

任何知道如何解决此问题的方法吗?

Any idea how to get this fixed?

谢谢

推荐答案

我认为问题出在ngsw-config中。 versionedFiles 下的 .css .js 条目可能与 .css 和如果名称中没有 .bundle .chunk ,则dist文件夹中的 .js 文件。在较新的Angular版本中,这些条目已替换为 / *。js / *。css ,而 dist 文件夹中的文件在进行生产时就没有 .bundle .chunk

I think the problem is in the ngsw-config. The .css and .js entries under versionedFiles may not match the .css and .js files in the dist folder if they don't have .bundle or .chunk in their names. In more recent versions of Angular those entries were replaced with "/*.js" and "/*.css", and the files in the dist folder don't have .bundle or .chunk when building for production.

所以,实际上问题是 .js .css 文件没有被缓存,并且无论何时更新服务器上的文件,该应用程序不再找到它们,并且浏览器在服务工作者可以加载缓存的文件,检测更改并更新文件之前抛出错误(因为它返回index.html)。

So, the problem actually is that the .js and .css files are not being cached and whenever the files on the server are updated, the app no longer finds them and the browser throws an error (because it returns the index.html) before the service worker can load the "cached" files, detect the changes and update the files.

在Angular 6中, versionedFiles 的行为与 files 相同,已被弃用。因此,您的ngsw-config.json应该如下所示:

In Angular 6, versionedFiles behaves the same as files and was deprecated. So, your ngsw-config.json should look like this:

{
  "index": "/index.html",
  "assetGroups": [{
    "name": "app",
    "installMode": "prefetch",
    "resources": {
      "files": [
        "/favicon.ico",
        "/index.html",
        "/manifest.json",
        "/*.css",
        "/*.js"
      ]
    }
  }, {
    "name": "assets",
    "installMode": "lazy",
    "updateMode": "prefetch",
    "resources": {
      "files": [
        "/assets/**"
      ]
    }
  }]
}

这篇关于在Angular Service worker中缓存index.html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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