Wikipedia para siempre
ShareCode
Permalink: http://www.treeweb.es/u/974/ 01/02/2011

ShareCode

1 /*/////////////////////////////////////////////////////////////////////////////2  //3  AJAX DEFINITION (BEGIN) //4  */5 /**6  * Description: Manage ajax connections with a queue model.7  * Author: gerardooscarjt@gmail.com8  * Date: 2013/31/019  * Typical use:10 11 var ajax = new Ajax();12 ajax.setUrl('http://example.com/path');13 ajax.setMethod('post');14 ajax.setData({'name':'a','age':'22'};15 ajax.callback.done = function(xhr) {16  // ...17 };18 ajax.callback.error = function(xhr) {19  // ...20 };21 ajax.send();22 23 */24 var Ajax = function() {25  26  Ajax.prototype.requests.push(this);27  28  this._id = Ajax.prototype.id_generator;29  Ajax.prototype.id_generator++;30  31  this.callback = {32  done:null,33  error:null,34  progress:null,35  presend:null36  };37  38  this._method = 'get';39  this._async = true;40  this._url = '';41  this._data = null;42  this._retries = 3;43  this._xhr = null;44  45 }46 47 Ajax.prototype.requests = [];48 Ajax.prototype.queue = [];49 Ajax.prototype.id_generator = 0;50 Ajax.prototype.concurrency_limit = 4;51 52 /// METHOD ///53 Ajax.prototype.setMethod = function(method) {54  if (!this.isQueued())55  this._method = method;56 };57 Ajax.prototype.getMethod = function(method) {58  return this._method;59 };60 61 /// URL ///62 Ajax.prototype.setUrl = function(url) {63  if (!this.isQueued())64  this._url = url;65 };66 Ajax.prototype.getUrl = function() {67  return this._url;68 };69 70 /// DATA ///71 Ajax.prototype.setData = function(data) {72  if (!this.isQueued())73  this._data = data;74 };75 Ajax.prototype.getData = function () {76  return this._data;77 };78 79 /// IS QUEUED ///80 Ajax.prototype.isQueued = function () {81  return Ajax.prototype.queue.indexOf(this) > -1;82 };83 84 Ajax.prototype.send = function() {85  if (!this.isQueued()) {86  //logger.log(this._id + ' no está en la cola: encolando...');87  ajax_stats[this._id+'.'+this._retries] = {};88  ajax_stats[this._id+'.'+this._retries].delay = new Date().getTime();89  Ajax.prototype.queue.push(this);90  Ajax._move();91  } else {92  //logger.log('ya está en la cola'); 93  }94  logger.show();95 };96 97 /**98  * Returns true if abort has been performed99 */100 Ajax.prototype.abort = function() {101  if ( null != this._xhr && this._xhr.readyState != 4) {102  // The request is on the way. It must be cancelled103  ajax_stats[that._id+'.'+that._retries].request = new Date().getTime();104  this._xhr.abort();105  delete this._xhr;106  this._xhr = null;107  this._retries--;108  //alert('aborted for ' + this._id);109  return true;110  } 111  //alert('aborted not needed for ' + this._id);112  return false;113 };114 115 116 /// STATIC METHODS ///117 118 // Abort all current requests119 Ajax._abort_all = function() {120  121  //alert('aborting all requests');122  123  for (var k in Ajax.prototype.requests) {124  var a = Ajax.prototype.requests[k];125  a.abort() && a.send();126  }127  128  129 };130 131 /* Move queue */132 Ajax._move = function() {133  134  if (window.navigator.onLine) {135  while (Ajax.prototype.concurrency_limit > 0 && Ajax.prototype.queue.length > 0) {136  var a = Ajax.prototype.queue.shift();137  a._send();138  //logger.log('Desencolado '+a._id);139  Ajax.prototype.concurrency_limit--;140  }141  }142 };143 144 /// PRIVATE METHODS (I WOULD LIKE) ///145 Ajax.prototype._send = function() {146  var that = this;147  148  //logger.log('Send request for '+this._id);149  150  this._xhr = new XMLHttpRequest({mozSystem:true});151  152  this._xhr.open(this._method, this._url, this._async);153  154  this._xhr.onreadystatechange = function(event) {155  if(that._xhr.readyState == XMLHttpRequest.DONE) {156  //logger.log('DONE! ' + that._id +' (delay '+that._xhr.responseText+')');157  ajax_stats[that._id+'.'+that._retries].request = new Date().getTime();158  ajax_stats[that._id+'.'+that._retries].server_delay = that._xhr.responseText;159  Ajax.prototype.concurrency_limit++;160  Ajax._move();161  }162  };163  164  this._xhr.onerror = function(event) {165  logger.log('ERROR! ' + that._id);166  Ajax.prototype.concurrency_limit++;167  Ajax._move();168  };169  170  this._xhr.send();171  ajax_stats[this._id+'.'+this._retries].waiting = new Date().getTime();172  173  174 };175 176 // Initialize onLine and offLine events177 window.addEventListener('online', function() {178  Ajax._move();179 }, true);180 181 window.addEventListener('offline', function() {182  Ajax._abort_all();183 }, true);184 185  /*186  AJAX DEFINITION (END) //187  //188 /////////////////////////////////////////////////////////////////////////////*/189 190 191 192 var ajax_stats_start = new Date().getTime();193 var ajax_stats = {};194 var line_status = [];195 196 197 198 199 window.addEventListener('load', function(){200  //test1(); 201  202  // Initialize onLine and offLine events203  window.addEventListener('online', function() {204  alert(1);205  line_status.push(new Date().getTime());206  }, true);207  208  window.addEventListener('offline', function() {209  alert(2);210  line_status.push(new Date().getTime());211  }, true);212  213  214  log_chart = logger.log('CHAT WILL RENDER HERE');215  216 }, true);217 218 219 /**220  * Launch 10 ajax calls221 */222 function test1() {223  224  ajax_stats_start = new Date().getTime();225  ajax_stats = {};226 227  logger.show();228 229  for (var i=0; i<10; i++) {230  var ajax = new Ajax();231  ajax.setUrl('http://www.treeweb.es/request?e='+ajax._id);232  ajax.callback.done = function(xhr) {233  logger.log('Completed '+ajax._id);234  };235  ajax.send();236  //logger.log('Launched '+ajax._id);237  }238 239  //logger.log(Ajax.prototype.queue);240  241  see_chart();242 }243 244 /**245  * Launch 20 fast ajax calls246 */247 function test2() {248  249  ajax_stats_start = new Date().getTime();250  ajax_stats = {};251 252  logger.show();253 254  for (var i=0; i<100; i++) {255  var ajax = new Ajax();256  ajax.setUrl('http://www.treeweb.es/request?e='+ajax._id);257  ajax.callback.done = function(xhr) {258  logger.log('Completed '+ajax._id);259  };260  ajax.send();261  //logger.log('Launched '+ajax._id);262  }263 264  //logger.log(Ajax.prototype.queue);265  266  see_chart();267 }268 269 function see_stats() {270  271  var s = '';272  273  for (k in ajax_stats) {274  s +=275  '<tr>'276  + '<td>' + (k) + ' (server delay ' + ajax_stats[k].server_delay + ')' + '</td>'277  + '<td>' + (ajax_stats[k].delay - ajax_stats_start) + '</td>'278  + '<td>' + (ajax_stats[k].waiting - ajax_stats[k].delay) + '</td>'279  + '<td>' + (ajax_stats[k].request - ajax_stats[k].waiting) + '</td>'280  + '</tr>';281  }282  283  var h = '<tr> <td>id</td> <td>delay</td> <td>waiting</td> <td>request</td> </tr>';284  s = '<table>' + h + s + '</table>';285  286  logger.log(s);287  logger.show();288 }289 290 var log_chart = null;291 292 293 function see_chart() {294  295  // Calc maximum time:296  /*297  var max_t = -1;298  var max_w = 1;299  for (k in ajax_stats)300  if (ajax_stats[k].request > max_t) {301  max_t = ajax_stats[k].request;302  max_w = ajax_stats[k].request - ajax_stats_start;303  }304  */305  306  max_w = new Date().getTime() - ajax_stats_start;307  308  var s = '';309  310  for (k in ajax_stats) {311  312  var delay_ms = ajax_stats[k].delay - ajax_stats_start;313  var waiting_ms = ajax_stats[k].waiting - ajax_stats[k].delay;314  var request_ms = ajax_stats[k].request - ajax_stats[k].waiting;315  316  var delay = (100 * Math.floor(1000*(delay_ms) / max_w ) / 1000);317  var waiting = (100 * Math.floor(1000*(waiting_ms) / max_w ) / 1000);318  var request = (100 * Math.floor(1000*(request_ms) / max_w ) / 1000);319  320  s += ''321  + '<div class="label">'322  + (k) + ' (delay ' + ajax_stats[k].server_delay + 's)' + '</div>'323  + '<div class="row">'324  + '<div class="bar bar-delay" style="width:' + delay + '%" title="' + delay + '%">' + delay_ms + 'ms</div>' 325  326  + '<div class="bar bar-waiting" style="width:' + waiting +'%" title="' + waiting +'%">' + waiting_ms + 'ms</div>'327  328  + '<div class="bar bar-request" style="width:' + request +'%" title="' + request +'%">' + request_ms + 'ms</div>'329  330  + '<div class="bar bar-end" ><div></div></div>'331 332  + '</div>';333  }334  335  s = '<div class="chart">' + s + '</div>';336 337  log_chart.innerHTML = s;338 339  340 341  logger.show();342  setTimeout(function() {343  see_chart();344  }, 500);345 }346 347 
Enlace
El enlace para compartir es:

Powered by TreeWeb
© TreeWeb 2010. Todos los derechos reservados