GoogleChrome / workbox

📦 Workbox: JavaScript libraries for Progressive Web Apps
https://developers.google.com/web/tools/workbox/
MIT License
12.3k stars 811 forks source link

How to correctly use of precacheAndRoute to serve index.html ? (how to precache current html?) #3337

Open eret9616 opened 3 months ago

eret9616 commented 3 months ago

Library Affected: workbox-sw, workbox-build

Browser & Platform: "all browsers"

Issue or Feature Request Description: My website is a single-page application, and Nginx uses try_files to return index.html for various routes. I've pre-cached index.html using Workbox. However, I've noticed that when I first visit a route, there is an initial document request, and then the service worker also makes another fetch request for index.html. These are two different requests with different durations,

and the service worker's fetch looks does not use the cache from the initial document request.( because i see the waterfall timeline in chrome devtool)

Is this expected behavior? How can I fix this issue so that only one request is necessary?

nginx.conf:

     location / {
            try_files $uri /index.html;
            add_header Cache-Control "no-cache,max-age=0";

workbox-config.js

module.exports = {
  globDirectory: 'dist',
  globPatterns: [
    'index.html',
...],
/ ...
}

service-worker.js:

...
precacheAndRoute(self.__WB_MANIFEST || [])
...
registerRoute(
  ({ request }) => {
    if (request.destination === 'document') {
        ...
        return true
      }
    }
    return false
  },
  async ({ request }) => {
    const response = await matchPrecache(`/index.html`)
    if (response) {
      return response
    } else {
      return fetch(request)
    }
  }
)
...