以编程方式缓存和无效 XHR/Ajax 响应

发布于 2024-10-04 17:21:45 字数 220 浏览 0 评论 0原文

考虑一个网页有大量对服务器的 XHR 调用,而一个 iframe 也包含大量对服务器的 XHR 调用。 许多此类调用都是相同的(冗余)。我确实有单一的通信接口(即 javascript 对象中的一组方法)。

如何优化服务器调用?我们可以缓存响应吗? (当发生某些可能改变响应的操作时,我可以使存储的响应无效),此外,页面刷新后应清除此缓存。有这样的组件/技术可用吗?

问候,
纳吉克特

Consider a webpage having lot of XHR calls to server and A iframe which again contains lot of XHR calls to server.
Many of this calls are same (Redundant). I do have single communication interface (i.e. set of methods in a javascript object).

How to optimize server calls? Can we cache responses? (I can invalidate stored response when some action happend which may change response), Also This cache should be cleared after page refresh. Is there any such component/technique available?

Regards,
Nachiket

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哆啦不做梦 2024-10-11 17:21:45

某种形式的记忆。
注意:您必须更改以下代码以适应您的 XHR 实施。
由于您没有提供代码,因此必须做出假设。

var cacheXHRWrapper = function ( url , handler ) {

   var cache = {};
   var queued = {};
   var pending = {};

   if ( cache[ url ] ) {

      handler( cache[ url ] );

   } else {

      queued[ url ] || ( queued[ url ] = [] ); // I know, call me lazy.
      queued[ url ].push( handler );

      if ( !pending[ url ] ) {

         // might want to adjust this to comply to your XHR implementation
         XHR_IMPL.request( url , function ( response ) {

            // cache response
            cache[ url ] = response;

            // serve all queued handlers.
            var fn = queued[ url ].shift();
            while ( fn ) {
               fn( response );
               fn = queued[ url ].shift();
            }

         } );

         pending[ url ] = true;

      }

   }
}

额外的好处是,队列请求处理程序(按 url)已在运行。

Some form of memoization.
NOTE: you will have to change the following code to accomodate your XHR implementation.
Had to make assumptions since you offered no code.

var cacheXHRWrapper = function ( url , handler ) {

   var cache = {};
   var queued = {};
   var pending = {};

   if ( cache[ url ] ) {

      handler( cache[ url ] );

   } else {

      queued[ url ] || ( queued[ url ] = [] ); // I know, call me lazy.
      queued[ url ].push( handler );

      if ( !pending[ url ] ) {

         // might want to adjust this to comply to your XHR implementation
         XHR_IMPL.request( url , function ( response ) {

            // cache response
            cache[ url ] = response;

            // serve all queued handlers.
            var fn = queued[ url ].shift();
            while ( fn ) {
               fn( response );
               fn = queued[ url ].shift();
            }

         } );

         pending[ url ] = true;

      }

   }
}

Bonus, queues request handlers (by url) that are already running.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文