メモ化の一種。注: 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 ごとに) キューに入れます。