如何通过使用serviceWorker来缓存ajax响应 [英] how to cache ajax response by using serviceWorker

查看:484
本文介绍了如何通过使用serviceWorker来缓存ajax响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用index.html中的ajax调用服务器数据.完美地获取那些数据.现在,我正在与服务人员一起工作.我可以缓存所有静态资产(图像,js,css),然后在Chrome开发者工具的应用程序"标签中的缓存的存储"中检查那些缓存的资产.我可以在网络"选项卡中看到那些资产也已被缓存(磁盘缓存).

I am calling server data by using ajax in index.html. It is perfectly fetching those data. Now, i am working with serviceworker. I can cache all the static assets(images,js,css) and check those cached assets in Cached storage in application tab in Chrome dev tools. I can see in Network tab also those assets are cached( disk cache).

现在,我想使用service worker来缓存那些ajax响应(图像文件数组).在网络"标签中,我可以看到它正在调用未缓存的url(类型:xhr).到目前为止,我已经尝试获取URL并将其缓存,但是无法做到这一点.

Now, I want to cache those ajax response(array of image files) using service worker. In network tab, i can see it is calling url (type : xhr ) not cached. I have tried so far to fetch the url and cache those but not able to do it.

这是我在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;
      }
    })());
  }
});

请帮助我,以缓存响应.

Please help me what are changes needed to cache the response.

推荐答案

您的fetch事件处理程序始于

if (event.request.mode === 'navigate') {
  // ...
}

这意味着仅当传入的fetch事件是针对

That means the code inside of it will only execute if the incoming fetch event is for a navigation request. Only the initial request for an HTML document when first loading a page is a navigation request. Your AJAX requests for other subresources are not navigation requests.

如果您除了要缓存导航请求的逻辑之外,还想缓存对index.cfm?action=main.appcache的请求,则可以在第一个语句之后添加另一个if语句,并检查该URL:

If you want to cache your requests for index.cfm?action=main.appcache in addition to your logic in place for navigation requests, you can add another if statement after your first one, and check for that 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
  }
});

这篇关于如何通过使用serviceWorker来缓存ajax响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆