use*_*927 8 javascript ajax jquery
我正在使用一个简单的jQuery AJAX函数,它在第一次调用时运行速度非常慢(10-15秒),然后每次在第一次调用后运行正常<1 - 2秒.我无法弄清楚为什么会发生这种情况,但需要尽可能加快速度.这是功能:
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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
我正在请求的API的一个例子是Giphy API.我不相信这是一个服务器问题,因为它只发生在第一次调用api然后后续调用很快.
任何想法为什么会发生这种情况以及可以采取哪些措施来加快运行速度?
考虑到整个问题Javascript(客户端)+ API(服务器端)可能会使诊断问题变得复杂,因此我建议获得更具体的答案是首先找出问题.
回答你的一般问题,原因是什么?:这可能是很多事情,但显着的是:
如何诊断(隔离):测量每个步骤的时间,它可以是您当前时间的简单打印.我会在以下步骤中打破它:
注意:步骤2和3可以一起使用.
如何缓解这种情况发生(它不能解决问题,但可以减轻问题):
| 归档时间: |
|
| 查看次数: |
1405 次 |
| 最近记录: |