我是PWA的新手,我正在训练一个简单的项目。在goole chrome上第一次运行之后,我更改了service worker中的cacheName const和index.html中的标题,以测试所有站点资产的重新缓存。从这里开始,缓存仍在创建,但它是空的,并且我得到了错误"Uncaught (in promise) TypeError: Request failed“,它指的是SW we const staticCacheName = 'site-static-v1‘声明的行。
SW的代码如下:
const staticCacheName = 'site-static-v2';
const assets = [
'./',
'./index.html',
'./index.js',
'./main.js',
'./style.css',
'https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/css/ol.css',
'https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/build/ol.js',
'https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.6.1/proj4.js',
'https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.6.1/proj4-src.js'
];
// install service worker
self.addEventListener('install', evt => {
console.log('service worker has been installed');
evt.waitUntil(
caches.open(staticCacheName).then(cache => {
console.log('caching shell assets');
cache.addAll(assets);
})
);
});
// activate event
self.addEventListener('activate', evt => {
console.log('service worker has been activated');
});
// fetch event
self.addEventListener('fetch', evt => {
evt.respondWith(
caches.match(evt.request).then(cacheRes => {
return cacheRes || fetch(evt.request);
})
);
});任何帮助都将不胜感激。
发布于 2020-11-29 15:21:53
问题出在您的资产数组中。它只将URLpath带到要缓存的文件,而不是文件路径。简而言之,去掉这些路径前面的点。
const assets = [
'/',
'/index.html',
'/index.js',
'/main.js',
'/style.css',
'https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/css/ol.css',
'https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/build/ol.js',
'https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.6.1/proj4.js',
'https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.6.1/proj4-src.js'
];如果您将js和css文件存储在以/static为路由的静态文件夹中,则需要在其中的每个文件前面添加/static。
我想再提一次,它只需要URLpath,而不需要FILEpath。它与您的文件路径无关。主要原因是它实际上缓存了服务器中的资产,而不是计算机中的资产。因此,它需要一个路由,而不是Filepath。
https://stackoverflow.com/questions/63701213
复制相似问题