【问题标题】:How to save images from network to cache using Fetch and Cache API如何使用 Fetch 和 Cache API 将图像从网络保存到缓存
【发布时间】:2016-06-27 19:45:49
【问题描述】:

我正在处理服务人员,在 fetch 事件中,我希望所有请求都保存在我的数组中,但是当我在控制台记录 fetch(event.request) 时,它只返回一个承诺。如何使用 fetch API 保存图像所有图像请求。我是服务工作者的新手。请帮忙。谢谢你。

  self.addEventListener('fetch', function(event) {
    event.respondWith(
        caches.match(event.request).then(function(response){
            if(response){
                return response; // get the element from the cache
            }
            /*save the fetch(event.request) link to array*/
            return fetch(event.request);// How toget the element from the network
        })
    );
});

【问题讨论】:

    标签: javascript caching fetch service-worker


    【解决方案1】:

    一件事是可视化您的响应,另一件事是存储响应对象(这是实际内容的总和,即图像和响应标头)。

    为了存储完整的响应,您应该使用cache objectput() 方法。

    要可视化响应的正文,您需要调用响应中的body methods 之一。

    如果要存储和可视化,则需要clone() 响应,因为存储或获取正文会导致响应不可读。

    这是fetch + update strategy 的链接。无论如何,我强烈建议您从 Service Worker guidetutorial 开始。

    【讨论】:

      猜你喜欢
      • 2011-05-07
      • 2021-03-28
      • 2021-06-03
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多