【发布时间】:2020-08-12 12:44:09
【问题描述】:
我有一个用 HTML、CSS 和 JS 和 Node.js 制作的 PWA,每次我更改应用程序的 styles.css 时,我都必须重新上传它,即更改端口。例如,在 localhost:3000 中,它将具有旧样式,但是如果我将其上传到 localhost:3100,则样式会更改为新样式,如何才能使缓存的 css 文件被删除并与新文件一起上传?
这是我的服务人员:
var CACHE_NAME = 'version-1'; // bump this version when you make changes.
// Put all your urls that you want to cache in this array
var urlsToCache = [
'index.html',
'assets/logo-192.png',
'images/airplane.png',
'images/backspace.png',
'images/calcToggle.png',
'images/diamond.png',
'images/favicon.png',
'images/hamburger.png',
'images/history.png',
'images/like.png',
'images/love.png',
'images/menu2.png',
'images/menu3.png',
'images/menu4.png',
'images/menu5.png',
'images/menu6.png',
'images/menu7.png',
'images/menu8.png',
'images/plane.png',
'images/science.png',
'images/settings.png',
'images/trash.png',
'styles.css'
];
// Install the service worker and open the cache and add files mentioned in array to cache
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
// keep fetching the requests from the user
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) return response;
return fetch(event.request);
})
);
});
self.addEventListener('activate', function(event) {
var cacheWhitelist = []; // add cache names which you do not want to delete
cacheWhitelist.push(CACHE_NAME);
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (!cacheWhitelist.includes(cacheName)) {
return caches.delete(cacheName);
}
})
);
})
);
});
【问题讨论】:
-
我们需要更多关于如何配置 PWA、是否使用 Service Worker 进行缓存以及缓存策略(如果有的话)的详细信息。
-
@Taplar 我添加了我的服务人员
-
var CACHE_NAME = 'version-1'; // bump this version when you make changes. -
与此相关的是,workbox (developers.google.com/web/tools/workbox) 已经预定义并维护了可以为您处理所有这些的缓存策略。
-
@Taplar 不敢相信我错过了!谢谢,你救了我的命!
标签: javascript html css node.js progressive-web-apps