我希望你能帮我解决我的问题。目前,我和一个服务工作者一起构建了一个PWA。注册成功,但安装有问题。
“caches.open”请求导致错误:"TypeError:-promise failed at“。你可以在Chrome中看到缓存是注册的,但是是空的。我已经检查过缓存urls上千次了..
这是我的服务工作者代码
var CACHE_NAME = 'surv-cache-1';
var resourcesToCache = [
'/',
'/index.html',
'/jquery-3.2.1.min.js',
'/pouchdb.min-6.4.1.js',
'/styles/inline.css',
'/scripts/app.js'
];
self.addEventListener('install', function(event) {
event.waitUntil(
// open the app browser cache
caches.open(CACHE_NAME).then(function(cache) {
console.log("Install succesfull");
// add all app assets to the cache
return cache.addAll(resourcesToCache);
}).then(function(out){
console.log(out);
}).catch(function(err){
console.log(err);
})
);
});
self.addEventListener('fetch', function(event) {
event.respondWith(
// try to find corresponding response in the cache
caches.match(event.request)
.then(function(response) {
if (response) {
// cache hit: return cached result
return response;
}
// not found: fetch resource from the server
return fetch(event.request);
}).catch(function(err){
console.log(err);
})
);
});还有我的注册码:
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js').then(function(registration) {
console.log('Service worker registered:'+registration.scope);
}).catch(function(e) {
console.log(e);
});
};
我不明白..。我希望您有一个想法:)
编辑:我想我现在知道为什么它不工作了。我的域有身份验证,所以不是每个人都可以访问它。当我的serviceworker想要缓存数据时,它得到了401。因此,这似乎是身份验证的问题。
也许有人已经有了同样的问题?
发布于 2018-05-09 18:12:26
当您的resourcesToCache包含返回404响应的内容时,就会发生这种情况。确保所有内容都输入正确。还要确保作用域是正确的。您可以使用以下命令检查worker作用域:
if("serviceWorker" in navigator) {
navigator.serviceWorker
.register(`worker.js`)
.then(registration => {
console.log("SW scope:", registration.scope);
});
}如果您的项目不在服务器域根目录中,执行以下操作可能会有所帮助:
//your main js
if("serviceWorker" in navigator) {
navigator.serviceWorker
.register(`${window.location.pathname}worker.js`)
.then(registration => {
//do your thing
});
}
//your worker js
let resourcesToCache = [
'./',
'./index.html',
'./jquery-3.2.1.min.js',
'./pouchdb.min-6.4.1.js',
'./styles/inline.css',
'./scripts/app.js',
];
//...作为附注,您应该从CDN加载您的库(jQuery,pouchdb),以提高性能。这些也可以缓存:
let resourcesToCache = [
'./',
'./index.html',
'https://code.jquery.com/jquery-3.3.1.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/pouchdb/6.4.3/pouchdb.min.js',
'./styles/inline.css',
'./scripts/app.js',
];发布于 2018-06-29 16:19:10
当我在windows机器上进行本地开发并在linux服务器上部署时,这种情况发生在我身上,问题出在路径上。您需要添加一个'.‘在您的路径之前,它类似于"./“,如下所示:
var resourcesToCache = [
'./',
'./index.html',
'./jquery-3.2.1.min.js',
'./pouchdb.min-6.4.1.js',
'./styles/inline.css',
'./scripts/app.js'];
发布于 2019-12-30 18:14:41
当我引用一个文件(该文件不存在于指定的路径中)进行缓存时,就发生了这种情况。当我更新文件的路径时,一切都变好了。
https://stackoverflow.com/questions/48828905
复制相似问题