大家好,我是这项技术的新手,我想为我的代码寻求帮助。我想做的是缓存 Assets 文件并从服务 worker 返回。
这是我用来注册 service worker 的代码
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/serviceworker.js')
.then(function(reg) {
// registration worked
console.log('Registration succeeded. Scope is ' + reg.scope);
}).catch(function(error) {
// registration failed
console.log('Registration failed with ' + error);
});
}
这是service worker里面的代码
importScripts('/cache-poli.js');
var CACHE_VERSION = 'app-v2';
var CACHE_FILES = [
'/',
'/js/plugins/bootstrap/js/bootstrap.min.js',
'/js/plugins/bootstrap-select/bootstrap-select.min.js',
'/js/plugins/prettyphoto/js/jquery.prettyPhoto.js',
'/js/plugins/jquery.sticky.min.js',
'/js/plugins/jquery.easing.min.js',
'/js/plugins/animate/js/animate.js',
'/js/jquery.fancybox.js',
'/js/plugins/jquery/jquery-ui-1.11.1.min.js',
'/js/jquery.scrollbar.min.js',
'/js/plugins/owlcarousel2/owl.carousel.min.js',
'/js/plugins/elevateZoom/jquery.elevateZoom-3.0.8.min.js',
'/js/theme.js',
'/js/cmsfuncs.js',
'/js/theme-config.js',
'/js/jquery.mCustomScrollbar.concat.min.js',
'/js/plugins/jquery/jquery-2.1.4.min.js',
'/js/jquery.cookie.js',
'/js/plugins/bootstrap/css/bootstrap.min.css',
'/fonts/fontawesome/css/font-awesome.min.css',
'/fonts/webfont/css/simple-line-icons.css',
'/fonts/elegantfont/css/elegantfont.css',
'/js/plugins/bootstrap-select/bootstrap-select.min.css',
'/js/plugins/owlcarousel2/assets/owl.carousel.min.css',
'/js/plugins/prettyphoto/css/prettyPhoto.css',
'/js/plugins/animate/css/animate.css',
'/s/plugins/accordion/css/magicaccordion.css',
'/css/jquery.scrollbar.css',
'/css/megamenu.css',
'/css/theme.css',
'/css/slider/slide.css',
'/css/jquery.mCustomScrollbar.css',
'/css/responsive.css',
'/css/theme.css'
];
self.addEventListener('install', function (event) {
event.waitUntil(
caches.open(CACHE_VERSION)
.then(function (cache) {
console.log('Opened cache');
return cache.addAll(CACHE_FILES);
})
);
});
self.addEventListener('activate', function (event) {
event.waitUntil(
caches.keys().then(function(keys){
return Promise.all(keys.map(function(key, i){
if(key !== CACHE_VERSION){
return caches.delete(keys[i]);
}
}))
})
)
});
self.addEventListener('fetch', function (event) {
event.respondWith(
caches.open(CACHE_VERSION).then(function(cache){
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
})
)
});
我使用 google chrome 开发工具来查看安装过程,一切都按应有的方式缓存,服务工作人员没有显示任何错误,但是当我再次尝试访问该网站时,它给了我一个错误。
无法访问此站点 domain.com 上的网页可能暂时无法访问,也可能已永久移动到新的网址。
最佳答案
我也有同样的错误。
实际上,这个问题是不言自明的。浏览器告诉您的是您尝试到达的路径不可到达。
在您的代码中,您似乎已经缓存了根 '/'
。我假设您在尝试访问诸如 '/somepath'
之类的其他路径时遇到了这个问题。
因为你没有缓存那些,所以你得到了这个错误。
所以在你的数组中,如果你还添加:
var CACHE_FILES = ['/',
'/somepath', ...];
错误不会发生。
我使用了完全相同的方法,错误消失了。
关于javascript - 使用 Service Worker 时无法访问站点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40038931/