Skip to content

Instantly share code, notes, and snippets.

@gunlee01
Forked from suprememoocow/intercept.js
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gunlee01/61526aa452684e67e065 to your computer and use it in GitHub Desktop.
Save gunlee01/61526aa452684e67e065 to your computer and use it in GitHub Desktop.
AJAX timing interceptor: this class intercepts all AJAX calls and records the time taken for the HTTP request to complete. These timings are posted back to the server in batches, if there are any to send, about every two seconds. Tested in Firefox, Chrome
(function(XHR) {
"use strict";
var stats = [];
var timeoutId = null;
var open = XHR.prototype.open;
var send = XHR.prototype.send;
XHR.prototype.open = function(method, url, async, user, pass) {
this._url = url;
open.call(this, method, url, async, user, pass);
};
XHR.prototype.send = function(data) {
var self = this;
var start;
var oldOnReadyStateChange;
var url = this._url;
function onReadyStateChange() {
if(self.readyState == 4 /* complete */) {
var time = new Date() - start;
stats.push({
url: url,
duration: time
});
if(!timeoutId) {
timeoutId = window.setTimeout(function() {
var xhr = new XHR();
xhr.noIntercept = true;
xhr.open("POST", "/clientAjaxStats", true);
xhr.setRequestHeader("Content-type","application/json");
xhr.send(JSON.stringify({ stats: stats } ));
timeoutId = null;
stats = [];
}, 2000);
}
}
if(oldOnReadyStateChange) {
oldOnReadyStateChange();
}
}
if(!this.noIntercept) {
start = new Date();
if(this.addEventListener) {
this.addEventListener("readystatechange", onReadyStateChange, false);
} else {
oldOnReadyStateChange = this.onreadystatechange;
this.onreadystatechange = onReadyStateChange;
}
}
send.call(this, data);
}
})(XMLHttpRequest);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment