2
votes

My Lighthouse Report suggests that I "Serve assets with an efficient cache policy". My problem is that my runtime.xxx.js, polyfills.xxx.js, main.xxx.js, and styles.xxx.js files need a longer cache lifetime than 1hr. Can a longer cache lifetime for these files be achieved using a Service Worker? If so, how?

I am using a ServiceWorker, which uses an ngsw-config file.

{
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "resources": {
        "files": [
          "/favicon.ico",
          "/index.html"
        ],
        "versionedFiles": [
          "/*.bundle.css",
          "/*.bundle.js",
          "*.js",
          "/*.chunk.js"
        ]
      },
      "cacheConfig": {
        "maxSize": 100,
        "maxAge": "86400",
        "strategy": "performance"
      }
    },
    {
      "name": "assets",
      "installMode": "lazy",
      "updateMode": "prefetch",
      "resources": {
        "files": [
          "/assets/**"
        ]
      }
    }
  ]
}

When I use Google Chrome DevTools and go offline, my application still shows. The Network tab shows that my styles.xxx.css is "(from Service Worker)", but my runtime.xxx.js, polyfills.xxx.js, and main.xxx.js are "(from memory cache)". When I click on runtime.xxx.js the Headers tab cache-control is max-age=3600. (Perhaps a default header setting is overriding my Service Worker.)

I've included the information from the Chrome Dev Tools Network tab when the app is offline. And my files are in dist/maldonado-a/. For example dist/maldonado-a/polyfills.xxx.js.

enter image description here

enter image description here

Please write to me if you need more information. Thank you.

1

1 Answers

2
votes

I think there is a little confusion between the caching done by the service worker, and what Lighthouse is reporting.

The cache setting is ngsw-config.config is referring to how long the Service Worker should keep a file cached (for offline use) before asking for it from the server again.

Lighthouse is referring to the HTTP cache header, which it is saying is too low. So from the Lighthouse docs, you should be setting the header to:

Cache-Control: max-age=31536000

Now this is outside of the realm of Angular ... it is your HTTP server's responsibility. How to set that up depends on what you are using: IIS, Apache, etc.

One option to consider with SPA (Single Page Applications) like Angular, is that if you put them on a CDN, then you get great caching (and a great Lighthouse score!).

Look at Azure CDN or Google CDN ... there is probably one from AWS too.