Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First ajax call goes extremely slow, subsequent calls run quickly -- why?

I'm using a simple jQuery AJAX function that runs extremely slow (10-15 seconds) the first time it's called, and then runs normally at <1 - 2 seconds each time it's called after that first time. I cannot figure out why this is happening but need to speed it up as much as possible. Here is the function:

function getNewItemAlt(apiUrl, callType, apiKey, dataType, returnValue, appendToWrapper) {
// ajax call to the api
  return $.ajax({
    type: callType,
    url: apiUrl,
    data: apiKey,
    dataType: dataType,
    success: function(result) {

        appendToWrapper.closest('.game_play_area').find('.game_loader').remove();

        // this is the thing that we want (probably either
        // an image url or an actual value)
        var desiredReturn = deepValue(result, returnValue);

        var specialClass = '';
        console.log(typeof desiredReturn)
        if (typeof desiredReturn === 'number') {
            specialClass = 'number'
        }

        // if it's a URL then it's an image and can be setup 
        // in an imgage tag and added to the dom
        if (desiredReturn.toString().substring(0, 4) == "http") {
            $(appendToWrapper).children('.game_image').remove();
            $(appendToWrapper).prepend('<img class="game_image" src="' + desiredReturn + '" />');
        } else {
            $(appendToWrapper).children('.game_value_return').remove();
            $(appendToWrapper).prepend('<p class="game_value_return ' + specialClass + '">' + desiredReturn + '</p>');
        }


        // clear the space to play the game
        // $(currentGameWrapper).children('.game_intro').remove();

        // show the game 
        // currentGameWrapper.children('.game_play_area').removeClass('hide');

    },
    error: function(err) {
        console.log(err);
    }
});
}

An example of an API that I'm making a request to is the Giphy API. I'm not convinced this is a server issue because it happens only on the first call to the api and then the subsequent calls are speedy.

Any ideas why this is happening and what can be done to make this run faster?

like image 235
user3006927 Avatar asked Mar 20 '17 17:03

user3006927


People also ask

Why AJAX response is slow?

There are two different types of issues that can cause admin-ajax. php slow server responses. The first is a backend CPU issue and the second is more of a frontend issue where you will notice third party plugins polling this file in your website speed tests.

How do I stop multiple AJAX calls from repeated clicks?

}); If isLoading is false, the AJAX call starts, and we immediately change its value to true. Once the AJAX response is received, we turn the value of that variable back to false, so that we can stop ignoring new clicks.

What happens when one AJAX call is still running and you send an another AJAX call before the data of first AJAX call comes back?

Since Ajax calls are asynchronous, the application will not 'pause' until an ajax call is complete, and simply start the next call immediately. JQuery offers a handler that is called when the call is successful, and another one if an error occurs during the call.

Are AJAX calls slow?

In my app, there are a lot of ajax calls. A user may do 50 ajax calls per session, so speed is very important. The ajax call queries the database and returns a list of records.


1 Answers

Considering the whole issue Javascript (client side) + API (server side) could complicate diagnosing the issue, so my suggestion to get a more specific answer would be to isolate the issue first.

Answering your general question, Reasons why?: It could be a lot of things but the remarkable ones are:

  1. Handshake: the first interaction between your page and the server makes the remote server to authenticate you and validate your session. Later calls wont go through that process.
  2. Server first execution: (less probable if you are using public APIs) if you are using a remote server with Java for example, that you are restarting, the first time you call a service it will load the instances, but for future calls those instances are already created hence they respond faster.
  3. Network: (I don't think so... but...) trace your HTTP request to see how many jumps it has and how much is taking for them to be resolved.

How to Diagnose (isolation): Measure the time each step takes, it could be a simple print of your current time. I would break it the in the following steps:

  1. Preparing the call to the API.
  2. Calling the API.
  3. Getting the data.
  4. Manipulate the received data on the client side.

NOTE: steps 2 and 3 could go together.

How to mitigate this from happening (it doesn't solve the issue, but mitigates it):

  1. Handshake: if the issue is related with authentication/authorization I recommend you to do an empty pre-fetch (without requesting any data) to deal with the handshake. Then you do a data fetch when you need it without that overhead.
  2. Server first execution: you don't have too much to do here unless you own the server also. In this case I recommend also a pre-fetch but calling the entire service to initialize the server objects.
  3. Javascript API: if the problem is dealing with the data on your client side then review how to optimize your Javascript code.
like image 59
Juan Castellon Avatar answered Sep 21 '22 23:09

Juan Castellon