views:

45

answers:

4

Hi folks,

Is there anyway to see how long a simple $.getJSON method takes to call using some type of timing code, in jquery/javascript?

Secondly, is there any way to see how BIG the response Content-Length is, in kB or megabytes?

+2  A: 

Try either Firebug or Fiddler

http://getfirebug.com/

http://www.fiddler2.com/fiddler2/

Aaron
I think, he want's to do it in javascript. Probably need to mess with response headers, not sure.
Nikita Rybak
+1 i wonder how we did web dev without firebug and fiddler. Oh yes I remember now it was *much* more tedious.
Byron Whitlock
Developer Tools in Chrome are also very good.
sje397
Not what i'm after. I'm after some JAVASCRIPT code. I know how to use firebug, etc.
Pure.Krome
+2  A: 

If you want pure javascript, right before you send the request note the time using new Date().getTime();

Then in the ajax callback, note the time again, and subtract against the first time. That will give you the length of the call.

Something like this:

function aCallback()
{
   window.time2 = new Date().getTime();
   window.alert(window.time2 - window.time1)
}
window.time1 = new Date().getTime();
$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: aCallback
});
Byron Whitlock
perfect :) Time to test this...
Pure.Krome
A: 

Why reinvent the wheel? Use firebug's console to log the time. Do something like this:

function aCallback()
{
   console.timeEnd("ajax call");
   window.alert(window.time2 - window.time1)
}
console.time("ajax call");
$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: aCallback
});

This will log how long it took until the server response gets back to the call. It will log the time in miliseconds to the firebug console.

Dale
I can't use the console because i need to display this to the client (ie. as text in the html). Clients won't have firebug, etc..
Pure.Krome
A: 

To answer your second question, you can read the Content-Length header from the XHR response.

var req;
req = $.ajax({
    type: "HEAD",
    url: "/data",
    success: function () {
      alert("Size is " + req.getResponseHeader("Content-Length"));
    }
});
Mr. X
AWESOME! I wish i could double-tick this :(
Pure.Krome