How to deal with browser's limit of parallel requests per domain in case of a priority AJAX request?

痴心易碎 提交于 2019-12-03 07:44:14

You can actually keep using the same XmlHttpRequest instance after aborting the request, calling the open and send methods again, and the event listeners remain attached. Updated the snippet with overloading the xhr open/send method to save the url and payload:

var pending_requests = [], 
    XHRBase = {
      open: XMLHttpRequest.prototype.open, 
      send: XMLHttpRequest.prototype.send
    };

XMLHttpRequest.prototype.open = function() {

  pending_requests.push(xhr._data = {xhr: this, open: arguments});
  XHRBase.open.apply(this, arguments);
  // add event listener to pop on finish
}

XMLHttpRequest.prototype.send = function() {
  xhr._data.send = arguments;
  XHRBase.send.apply(this, arguments);
}

function priority_call(params, callback) {
  pending_requests.forEach((req) => req.xhr.abort());
  // do vip xhr
  pending_requests.forEach((req) => {
    XHRBase.open.apply(req.xhr, req.open); 
    XHRBase.send.apply(req.xhr, req.send);
  })
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!