Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ajax speed vs direct access speed

I have a web service written using the Pyramid framework and a frontend written using jQuery and jQuery Mobile. What I have noticed is that some of the Ajax calls take about 5-10 times longer to complete using the Ajax method over directly going to the URL in a browser.

My Ajax code looks like this, shortened for brevity:

$.ajax({
      url:address,
      dataType:'jsonp',
      crossDomain: true,
      success: function(data)
      {
          Parsing and other stuff that takes some time...
      }});

Now, I fire about 10 of these at once, to different URLs, which could be the reason for the slower response, but if I fire just one at a time it is still about 3 times slower. (30ms vs 90ms). I have tried using the waitress in Pyramid, as well as mod_wsgi (1 process, 4 threads) with about the same result.

My question is: where is the overhead coming from? Pyramid? Web server? jQuery? jQM? .ajax()? What can I do, if anything to decrease the request time?

Edit: Switching between JSON and JSONP has little effect, but the further testing has shown that the time is very variable (50ms to 100ms) from test to test. However, the direct access to the service through browser is always 30ms +/- 1 ms.

I have tested this with Firebug, Chrome Web Dev tool, and Fiddler with similar results. When replicating one of the requests in Fiddler, I get a similar result to that of going directly to the resource in a browser.

Here is a screencap from Firebug of a run where I'm purposefully trying to make it slower by running the 9 calls 5 times each: http://s16.postimage.org/n6t5z1ow5/ajax_Cap.png hope that can give some more hints. Grey is "blocking", purple is "waiting".

like image 611
Lars Avatar asked Nov 14 '22 09:11

Lars


1 Answers

I'm guessing that the problem is the crossdomain/jsonp option - as this is a 'fake' ajax request to get around browser security restrictions.

What JQuery is doing here is creating a script element with the source set to the URL you supplied in the call (and some other stuff, wrapping the returned data in a function call), so almost certainly there is some weirdness / slowness going on. If I remember right, the browser actually blocks script execution while it's loading script blocks too...?

You could try to get around this by including in your service a "Access-Control-Allow-Origin" header set to '*' (allows all access), and taking out all your 'crossdomain' stuff.

like image 178
dmp Avatar answered Dec 25 '22 13:12

dmp