I’m creating an application based around the Twitter API 1.1. User defined Twitter profile images are pulled in and displayed in the app, and once clicked the latest tweet of the particular account is displayed. Currently this process is initiated on click, using AJAX and a ‘for each’ loop which finds and displays the correct tweet included in a separate php page.
Although this process works fine, once the user has clicked on a profile image the app takes far too long to load the required tweet. I need some advice on how to optimise the process of loading tweets? Perhaps it might not need to be dependent on click, but I’m just not sure how to optimise my code.
Any help will be greatly appreciated.
Here’s the code to help your understanding:
Code which initiates the latest tweet dependent on a particular profile image:
// Create all Tweeter objects
foreach ($tweeters as $i => $tweeter){
$tweeters[$i] = new Tweeter($tweeter, $tmhOAuth);
}
// Display all Tweeters
foreach ($tweeters as $tweeter){
$r+=1;
echo '<a class="fancybox fancybox.ajax" href="tweets.php #' . $r . '">';
echo '<img class="tweetTime' . $r . '" id="' . $r . '" src="' . $tweeter->getImage() . '" width="240px" height="240px" /></a>';
}
Code that gets the tweets in a separate page:
require_once('config/FrameFunctions.php');
foreach ($tweeters as $i => $tweeter){
$tweeters[$i] = new Tweeter($tweeter, $tmhOAuth);
}
foreach ($tweeters as $tweeter){
$r+=1;
echo '<div id="' . $r . '"><p>Latest tweet from <b>' . $tweeter->getName() . '</b>:<br />';
foreach ($tweeter->getTweets() as $tweet){
echo $tweet['text'] . '<br />';
echo "Sent: <b>" . $tweet['created_at'] . "</b></p></div>";
}
}
You need to decouple the tweet retrieval from the user click. Move the AJAX to a JQuery ajax() call set to run at intervals. Add a hidden element to hold the latest tweets and update that with the result of the AJAX call. Also change the fancybox call to use the content of the hidden elements instead of having the fancybox making the AJAX call.
Main HTML:
Update Tweets code (Ajax php) :