GoogleChrome / GoogleChrome/workbox

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

Open
#3,337 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
13k
Forks
880
Avg merge
2h 44m
Merged PRs (30d)
8

Description

**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)
}
}
)
...
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.