Tuesday, 13 August 2013

Faster API calls with Javascript

Faster API calls with Javascript

I'm making an app called "Your Life in Music" where the user plugs in
his/her birthdate and the app displays the top billboard hit from each
birthday since they were born. The app is currently pretty slow since it
takes a while to retrieve all the album cover images from the Last.fm api.
I'm wondering how one can speed up API calls with JS/jQuery. It seems like
threading might solve this but I'm not sure how to implement that...
Here's the app: http://www.dailyspiro.com
And the critical code:
function compileDisplay(birthDays) {
// create an HTML list that for each birthday displays top song,
artist, and album art
htmlObj = {}
for (i = 0; i < birthDays.length; i++) {
var age = birthDays[i][0]; // age isn't equal to i if user was
born before 1958
var date = birthDays[i][1];
try {
var track = billboard[date]['song'];
} catch (err) {
console.log(date)
}
var artist = billboard[date]['artist'];
getAlbumArt(age, track, artist, birthDays);
}
}
function getAlbumArt(age, track, artist, birthDays) {
$.getJSON("http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=6ad5bad28ffc4dedbcf1115b3ddf5273&artist="
+ artist + "&track=" + track + "&format=json&callback=?", function
(data) {
try {
var image = data.track.album.image[2]['#text'];
if (image ==
'http://cdn.last.fm/flatness/catalogue/noimage/2/default_album_medium.png')
{
throw 'generic image';
}
} catch (err) {
var image = 'images/' + track + '.jpg';
}
compileHtml(age, track, artist, image, birthDays)
})
}

No comments:

Post a Comment