问题
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¶m3=value3
Is it possible to cache this as 'maps.googleapi.com/js'
and while fetching inject last used params ?
回答1:
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.
);
}
}
回答2:
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
来源:https://stackoverflow.com/questions/27915193/how-to-cache-apis-like-google-maps-while-using-service-workers