New*_*bie 0 service-worker progressive-web-apps
我正在开发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);
})
);
});
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
Uncaught (in promise) TypeError: Request failed (sw.js:1)
Run Code Online (Sandbox Code Playgroud)
我不明白为什么它在本地工作时无法在线缓存我的文件(github页面).有人可以帮我理解吗?
谢谢.
编辑:我试图通过Netlify部署该网站,它在那里工作.所以它必须与Github页面有关.我还是想知道它是什么,如果有人可以放弃任何光线.
如本地Service Worker缓存中所述但在线失败,在部署时gh-pages,您的Web应用程序的内容通常将从域的路径而不是顶级路径中访问.
例如,如果您的文件位于其gh-pages分支中https://github.com/<user>/<repo>,则可以从中访问您的Web内容https://<user>.github.io/<repo>/.
鉴于您可以访问所有内容,cacheFiles阵列中的所有URL 都以前缀为准/,这不是您想要的/<repo>/.例如,/被解释为https://<user>.github.io/,与之不同https://<user>.github.io/<repo>/.
您的问题的解决方案将导致配置无论基本URL对于您的托管环境是什么有效,都是在您的每个URL之前./而不是/.例如:
const cacheFiles = [
'./',
'./css/styles.css',
// etc.
];
Run Code Online (Sandbox Code Playgroud)
这./意味着URL是相对的,服务工作者文件的位置用作基础.您的服务工作者文件将部署在其下https://<user>.github.io/<repo>/,因此最终将成为用于其余内容的正确基本URL.
| 归档时间: |
|
| 查看次数: |
655 次 |
| 最近记录: |