Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

444
Visualizações
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?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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.
over 4 years ago · Santiago Trujillo Relatório

0

This might be a long shot. "appendToWrapper" is an object passed in by reference. If it's taking a long time to resolve (ie it takes 10 seconds or so to find ".game_play_area" etc... in the DOM) then it would be slow the first time, but saved in the calling function and fast subsequent times.

It might be easy to check. If you could make a deep copy of the object before passing it in, we would expect the AJAX to be slow every time, not just the first time. If that's the case, you'd need to clean up your selectors to make them faster. Perhaps use ids instead of classes.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda