3

Trying to cache Google Maps API response in Service Workers.

Source Code: https://github.com/boopathi/sw-demo-iss/blob/gh-pages/sw.js

Now I'm using all of the URLs that the Maps API would request to, but seems like a bad way, and I'm not able to cache everything, can I cache requests of some type and respond to requests of the same type.

say,

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

Is it possible to cache this as 'maps.googleapi.com/js' and while fetching inject last used params ?

Boopathi Rajaa
  • 4,659
  • 2
  • 31
  • 53

2 Answers2

6

You can include logic in your fetch handler that examines event.request.url and takes whatever arbitrary action you'd like to return a Response from a cache, or even create a new Response on the fly.

Something along the lines of:

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.
    );
  }
}
rmNyro
  • 351
  • 2
  • 14
Jeff Posnick
  • 53,580
  • 14
  • 141
  • 167
0

Modify the service worker config in ngsw-config.json to cache resources from maps.googleapi.com:

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

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

Raschid JFR
  • 580
  • 8
  • 15