我正在开发PWA,我已经在我的网站上安装并激活了一名服务工作者。它在本地服务器上进行测试时运行良好,但是当我实时发送代码时,它会失败。
这是我的SW:
const cacheName = 'v1';
const cacheFiles = [
'/',
'/css/styles.css',
'/images/test1.png',
'/images/test2.png',
'/js/app.js',
'/js/sw-registration.js'
]
// Install event
self.addEventListener('install', function(event) {
console.log("SW installed");
event.waitUntil(
caches.open(cacheName)
.then(function(cache){
console.log('SW caching cachefiles');
return cache.addAll(cacheFiles);
})
)
});
// Activate event
self.addEventListener('activate', function(event) {
console.log("SW activated");
event.waitUntil(
caches.keys()
.then(function(cacheNames){
return Promise.all(cacheNames.map(function(thisCacheName){
if(thisCacheName !== cacheName){
console.log('SW Removing cached files from', thisCacheName);
return caches.delete(thisCacheName);
}
}))
})
)
});
// Fetch event
self.addEventListener('fetch', function(event) {
console.log("SW fetching", event.request.url);
event.respondWith(
caches.match(event.request)
.then(function(response){
console.log('Fetching new files');
return response || fetch(event.request);
})
);
});
这是我得到的错误:
Uncaught (in promise) TypeError: Request failed (sw.js:1)
我不明白为什么它在本地工作时无法在线缓存我的文件(github页面)。有人可以帮我理解吗?
谢谢。
编辑:我试图通过Netlify部署网站,它在那里工作。所以它必须与Github页面有关。我还是想知道它是什么,如果有人能放下任何光明。答案 0 :(得分:7)
正如Service Worker caches locally but fails online中所述,在部署到gh-pages
时,您的网络应用内容通常会从该路径的子路径而不是顶级路径中访问。
例如,如果您的文件位于gh-pages
的{{1}}分支中,则可以从https://github.com/<user>/<repo>
访问您的网络内容。
https://<user>.github.io/<repo>/
数组中的所有网址都以cacheFiles
为前缀,这不是您想要的,因为您可以在/
下访问所有内容。例如,/<repo>/
被解释为/
,与https://<user>.github.io/
不同。
您的问题的解决方案是使用https://<user>.github.io/<repo>/
而不是./
添加每个网址,这将导致配置无论基本网址对于您的托管环境有效。例如:
/
const cacheFiles = [
'./',
'./css/styles.css',
// etc.
];
表示URL是相对的,服务工作者文件的位置用作基础。您的服务工作者文件将部署在./
下,因此最终将成为用于其他内容的正确基本URL。