一起或单独加载远程项目?

时间:2012-04-22 16:10:48

标签: php ajax api optimization call

我正在寻找优化我的应用程序。它使用Twitter和Facebook API并加载大文件以显示在用户屏幕上。现在,我正在线性运行脚本,调用一个文件,其中包含使用AJAX的API调用并将所有信息加载到屏幕上。将两个API调用分成两个不同的文件,然后用AJAX分别加载每个文件,我会更快吗?这样,如果一个响应比另一个响应时间更长,则仍然会显示更快的响应。

谢谢。

如果重要,我正在使用PHP和CURL进行API调用。

1 个答案:

答案 0 :(得分:1)

当然,如果AJAX调用不相互依赖会更好。您也可以在PHP端使用curl_multi_init在并行执行HTTP调用。

PHP手册中的示例:

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$active = null;
//execute the handles
do {
     $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {
    if (curl_multi_select($mh) != -1) {
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    }
}

//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

?>