【问题标题】:How to cache APIs like Google Maps while using Service Workers如何在使用 Service Worker 时缓存 Google Maps 等 API
【发布时间】:2015-03-10 23:58:12
【问题描述】:

尝试在 Service Worker 中缓存 Google Maps API 响应。

源代码:https://github.com/boopathi/sw-demo-iss/blob/gh-pages/sw.js

现在我正在使用 Maps API 会请求的所有 URL,但这似乎是一种不好的方法,而且我无法缓存所有内容,我可以缓存某种类型的请求并响应同类型。

说,

GET maps.googleapi.com/js?param1=value1
#and
GET maps.googleapi.com/js?param2=value2&param3=value3

是否可以将其缓存为 'maps.googleapi.com/js' 并在获取注入最后使用的参数时?

【问题讨论】:

    标签: service-worker


    【解决方案1】:

    您可以在您的fetch 处理程序中包含逻辑,该处理程序检查event.request.url 并采取任何您想从缓存中返回Response 的任意操作,甚至可以即时创建一个新的Response

    类似的东西:

    self.addEventListener('fetch', function(event) {
      if (event.request.url.indexOf('https://maps.googleapi.com/js') == 0) {
        event.respondWith(
          // Handle Maps API requests in a generic fashion,
          // by returning a Promise that resolves to a Response.
        );
      } else {
        event.respondWith(
          // Some default handling.
        );
      }
    }
    

    【讨论】:

      【解决方案2】:

      修改 ngsw-config.json 中的 service worker 配置以缓存来自 maps.googleapi.com 的资源:

      // ngsw-config.json
      {
        "assetGroups": [
          "urls": [
            "https://maps.googleapis.com/js*"
          ]
        ]
        ...
      }
      

      参考:https://angular.io/guide/service-worker-config#urls

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-22
        • 1970-01-01
        • 2018-03-28
        相关资源
        最近更新 更多