如何在使用Service Workers时缓存像Google Maps这样的API

3
尝试在Service Workers中缓存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'并在获取时注入上次使用的参数?

2个回答

6
您可以在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.
    );
  }
}

0

ngsw-config.json中修改服务工作者配置,以缓存来自maps.googleapi.com的资源:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接