如何在使用 Service Workers 时缓存像 Google Maps 这样的 API [英] How to cache APIs like Google Maps while using Service Workers
问题描述
尝试在 Service Workers 中缓存 Google Maps API 响应.
Trying to cache Google Maps API response in Service Workers.
源代码:https://github.com/boopathi/sw-demo-iss/blob/gh-pages/sw.js
现在我正在使用 Maps API 请求的所有 URL,但似乎是一种糟糕的方式,而且我无法缓存所有内容,我可以缓存某种类型的请求并响应同类型.
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.
说,
GET maps.googleapi.com/js?param1=value1
#and
GET maps.googleapi.com/js?param2=value2¶m3=value3
是否可以将其缓存为 'maps.googleapi.com/js'
并同时获取注入最后使用的参数?
Is it possible to cache this as 'maps.googleapi.com/js'
and while fetching inject last used params ?
推荐答案
您可以在您的 fetch
处理程序中包含逻辑,该处理程序检查 event.request.url
并接受任意任意您希望从缓存中返回 Response
的操作,或者甚至动态创建新的 Response
.
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.
大致如下:
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.
);
}
}
这篇关于如何在使用 Service Workers 时缓存像 Google Maps 这样的 API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!