我制作了一个Web应用程序,并在我的应用程序中使用了Service Worker。联机时一切正常。首次运行该应用程序时,所有文件均已缓存。但是当它脱机时,我会收到此错误。
Uncaught (in promise) TypeError: Failed to fetch
我不知道为什么会发生此错误!
我已经使用pwabuilder.com将服务人员和 list 添加到Web应用程序中。
这是pwabuilder-sw.js文件:
self.addEventListener('install', function(event) {
event.waitUntil(preLoad());
});
var preLoad = function() {
console.log('[PWA Builder] Install Event processing');
return caches.open('pwabuilder-offline').then(function(cache) {
console.log('[PWA Builder] Cached index and offline page during
Install');
return cache.addAll([
'/manup.js',
'pwabuilder-sw-register.js',
'pwabuilder-sw.js',
'manifest.json',
'/js/angular.min.js',
'/js/script.js',
'/js/materialize.min.js',
'/css/materialize.min.css',
'/css/style.css',
'/offline.html',
'/index.html'
]);
});
}
self.addEventListener('fetch', function(event) {
console.log('The service worker is serving the asset.');
event.respondWith(checkResponse(event.request).catch(function() {
return returnFromCache(event.request)
}));
event.waitUntil(addToCache(event.request));
});
var checkResponse = function(request) {
return new Promise(function(fulfill, reject) {
fetch(request).then(function(response) {
if (response.status !== 404) {
fulfill(response)
} else {
reject()
}
}, reject)
});
};
var addToCache = function(request) {
return caches.open('pwabuilder-offline').then(function(cache) {
return fetch(request).then(function(response) {
console.log('[PWA Builder] add page to offline' + response.url)
return cache.put(request, response);
});
});
};
var returnFromCache = function(request) {
return caches.open('pwabuilder-offline').then(function(cache) {
return cache.match(request).then(function(matching) {
if (!matching || matching.status == 404) {
return cache.match('offline.html')
} else {
return matching
}
});
});
};
这是pwabuilder-sw-register.js文件:
if (navigator.serviceWorker.controller) {
console.log('[PWA Builder] active service worker found, no need to register')
} else {
//Register the ServiceWorker
navigator.serviceWorker.register('pwabuilder-sw.js', {
scope: './'
}).then(function (reg) {
console.log('Service worker has been registered for scope:' +
reg.scope);
});
}
有任何线索吗?
最佳答案
我尝试缓存整个目录而不是单个文件时遇到了同样的错误。
我的猜测是,您有一个无法缓存的URL,因此整个缓存操作也会失败,并且缓存是原子含义:如果单个URL失败,则整个缓存都会失败。