我在index.html中使用ajax调用服务器数据。它正在完美地获取这些数据。现在,我正在与服务人员一起工作。我可以缓存所有静态资源(图像、js、css),并在 Chrome 开发工具的应用程序选项卡的缓存存储中检查这些缓存的资源。我可以在“网络”选项卡中看到这些 Assets 也被缓存(磁盘缓存)。
现在,我想使用服务工作线程缓存这些 ajax 响应(图像文件数组)。在网络选项卡中,我可以看到它正在调用未缓存的 url (类型: xhr )。到目前为止,我已尝试获取网址并缓存它们,但无法做到这一点。
这是我在index.html中的ajax调用
<script type="text/javascript">
$(document).ready(function () {
var url = 'index.cfm?action=main.appcache';
$.ajax({
type:"GET",
url: url,
data: function(data){
var resData = JSON.stringify(data);
},
cache: true,
complete: doSomething
})
});
function doSomething(data) {
console.log(data.responseText);
}
</script>
这是我的 serviceWorker 获取事件:
self.addEventListener('fetch', (event) => {
if (event.request.mode === 'navigate') {
event.respondWith((async () => {
try {
const preloadResponse = await event.preloadResponse;
if (preloadResponse) {
return preloadResponse;
}
const normalizedUrl = new URL(event.request.url);
if(normalizedUrl.endsWith === 'index.cfm?action=main.appcache'){
const fetchResponseP = fetch(normalizedUrl);
const fetchResponseCloneP = fetchResponseP.then(r => r.clone());
event.waitUntil(async function() {
const cache = await caches.open(precacheName);
await cache.put(normalizedUrl, await fetchResponseCloneP);
}());
return (await caches.match(normalizedUrl)) || fetchResponseP;
}
const networkResponse = await fetch(event.request);
return networkResponse;
} catch (error) {
console.log('Fetch failed; returning offline page instead.', error);
const cache = await caches.open(precacheName);
const cachedResponse = await cache.match(offlineDefaultPage);
return cachedResponse;
}
})());
}
});
请帮助我缓存响应需要进行哪些更改。
最佳答案
您的 fetch
事件处理程序以以下内容开头
if (event.request.mode === 'navigate') {
// ...
}
这意味着只有传入的 fetch
事件针对 navigation request 时才会执行其中的代码。 。只有首次加载页面时对 HTML 文档的初始请求才是导航请求。您对其他子资源的 AJAX 请求不是导航请求。
如果除了导航请求的逻辑之外,您还想缓存对 index.cfm?action=main.appcache
的请求,您可以添加另一个 if
在第一个语句之后声明,并检查该 URL:
self.addEventListener('fetch', (event) => {
if (event.request.mode === 'navigate') {
// ...
}
if (event.request.url.endsWith('index.cfm?action=main.appcache')) {
// Your caching logic goes here. See:
// https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook#serving-suggestions
}
});
关于javascript - 如何使用serviceWorker缓存ajax响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61193797/