【问题标题】:Is there any way to cache multiple files in PWA?有没有办法在 PWA 中缓存多个文件?
【发布时间】:2019-11-08 12:05:41
【问题描述】:

当用户在他的设备上“安装” PWA 时,有办法下载资产文件夹吗?我有大约 300MB 的图像(地图图块)需要为用户预先缓存,我的用户将在一个没有连接的区域中。而且我想知道这个“安装”是否会创建一些我可以将图像下载到的本地文件夹,或者不幸的是,我需要原生...

我已经尝试了一些与我的地图解决方案 (leaflet) 一起使用的库,但这些库仅以 blob 格式缓存 IndexedDB 中的 PNG,我认为这不是处理大量数据的好解决方案。

【问题讨论】:

    标签: javascript caching filesystems progressive-web-apps


    【解决方案1】:

    您可以使用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);
        })
      );
    });
    

    但请记住,这种策略通常用于应用外壳文件(远小于 300MB)。如果 Service Worker 无法下载您为“安装”阶段定义的资源,它将中止安装。

    一旦您的文件在缓存中,您就可以将它们提供给用户:

    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
        })
      );
    });
    

    【讨论】:

    • 我明白了,这就是我现在正在做的,但我只允许缓存大约 50MB,因为配额......所以我相信我需要原生......
    猜你喜欢
    • 2020-12-11
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-21
    • 2020-03-17
    • 2020-08-27
    • 2014-11-12
    相关资源
    最近更新 更多