2010-11-24 25 views
0

考虑一个网页,它有很多XHR调用服务器和一个iframe,其中又包含很多XHR调用服务器。 许多这种调用是相同的(冗余)。我有单一的通信接口(即在一个JavaScript对象中的一组方法)。以编程方式缓存并使XHR/Ajax响应无效

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

问候,
Nachiket

回答

-1

某种形式的记忆化的。 注意:您将不得不更改以下代码以适应您的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)已经运行。

相关问题