能否将index.html与service-worker.js分放不同目录?缓存资源失败求助
Hey there! Let's break down your two questions with clear, actionable steps:
1. Can index.html and service-worker.js be placed in different folders?
Absolutely! You don’t need to keep these two files in the same directory, but there’s a critical detail to nail down: the service worker’s scope.
By default, a service worker can only control pages and resources that live in its own directory or subdirectories. For example, if your service-worker.js lives in /sw/, its default scope is /sw/—meaning it can’t control your root-level index.html unless you adjust the scope.
To fix this, you have two key steps:
- When registering the service worker (usually in your
index.js), specify the desired scope using thescopeoption:navigator.serviceWorker.register('/sw/service-worker.js', { scope: '/' }) .then(reg => console.log('Service worker registered:', reg)) .catch(err => console.error('Registration failed:', err)); - Configure your server to send the
Service-Worker-Allowed: /HTTP header when servingservice-worker.js. This tells the browser the service worker is permitted to control your entire origin, not just its default directory.
2. Troubleshooting failed caching of index.js and mycss.css
Since you can’t place service-worker.js at the same level as index.html, the scope issue is likely the root cause of your caching failures. Here’s how to fix it:
First, confirm you’ve set up the scope correctly as outlined in the first question. Then, double-check your service worker’s caching logic:
If your file structure looks like this:
/ ├── index.html ├── index.js ├── mycss.css └── sw/ └── service-worker.js
Your service-worker.js should reference assets using absolute paths (relative to the root, since we set scope to /):
const CACHE_NAME = 'my-site-cache-v1'; const ASSETS_TO_CACHE = [ '/index.html', '/index.js', '/mycss.css' ]; self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME) .then(cache => { console.log('Opened cache'); return cache.addAll(ASSETS_TO_CACHE); }) .catch(err => console.error('Caching failed:', err)) ); });
Additional checks to rule out issues:
- Open your browser’s DevTools (Application > Service Workers) to confirm the service worker is registered and activated. Check the Cache Storage tab to see if assets are being added.
- Double-check for typos in your
ASSETS_TO_CACHEpaths—even a capitalization mismatch (like/MyCss.cssinstead of/mycss.css) will break caching. - Ensure your server is correctly sending the
Service-Worker-Allowedheader forservice-worker.js—without this, the browser will block access to resources outside the default scope.
内容的提问来源于stack exchange,提问作者swarup

