开发者

Caching and invalidating XHR/Ajax response programmatically

Consider a webpage having lot of XHR calls to server and A iframe which again contains lot of XHR call开发者_运维百科s 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜