有没有办法在 PWA 中缓存多个文件?
Is there any way to cache multiple files in PWA?
当用户 "install" 在他的设备上安装 PWA 时,有一种方法可以下载资产文件夹吗?我有大约 300MB 的图像(地图图块)需要为用户预缓存,我的用户将在一个没有连接的区域。我想知道这个 "installation" 是否创建了一些我可以将图像下载到的本地文件夹,或者不幸的是,我需要本地化...
我已经尝试了一些适用于我的地图解决方案的库 (leaflet
),但这些库仅以 blob 格式缓存 IndexedDB
中的 PNG,我认为这不是一个好主意海量数据的解决方案。
您可以使用 pre-fecth
策略来确保在安装 service worker 时所有静态资产都已下载并在缓存中可用:
const mapTilesToCache = [
'/mapFolder/',
];
const staticCacheName = 'tiles-cache';
self.addEventListener('install', event => {
event.waitUntil(
caches.open(staticCacheName)
.then(cache => {
return cache.addAll(mapTilesToCache);
})
);
});
但是请记住,这种策略通常用于应用 shell 文件(远小于 300MB)。如果 Service Worker 无法下载您为 "install" 阶段定义的资源,它将中止安装。
一旦您的文件在缓存中,您就可以将它们提供给用户:
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => {
if (response) {
// return the file from the cache
return response;
}
}).catch(error => {
// Respond with custom offline page
})
);
});
当用户 "install" 在他的设备上安装 PWA 时,有一种方法可以下载资产文件夹吗?我有大约 300MB 的图像(地图图块)需要为用户预缓存,我的用户将在一个没有连接的区域。我想知道这个 "installation" 是否创建了一些我可以将图像下载到的本地文件夹,或者不幸的是,我需要本地化...
我已经尝试了一些适用于我的地图解决方案的库 (leaflet
),但这些库仅以 blob 格式缓存 IndexedDB
中的 PNG,我认为这不是一个好主意海量数据的解决方案。
您可以使用 pre-fecth
策略来确保在安装 service worker 时所有静态资产都已下载并在缓存中可用:
const mapTilesToCache = [
'/mapFolder/',
];
const staticCacheName = 'tiles-cache';
self.addEventListener('install', event => {
event.waitUntil(
caches.open(staticCacheName)
.then(cache => {
return cache.addAll(mapTilesToCache);
})
);
});
但是请记住,这种策略通常用于应用 shell 文件(远小于 300MB)。如果 Service Worker 无法下载您为 "install" 阶段定义的资源,它将中止安装。
一旦您的文件在缓存中,您就可以将它们提供给用户:
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => {
if (response) {
// return the file from the cache
return response;
}
}).catch(error => {
// Respond with custom offline page
})
);
});