Using Web Workers to consume Lastfm API

By | 1 December, 2013

Web workers are a technology which allows us to delegate tasks in background using client-side programming. Until now with pure Javascript it was not possible to start or run multiple tasks at the same time. Web workers provide an easy way to split tasks in different contexts.

How this works is rather simple. From your Javascript app you just create a worker and pass it a message and the data you need. The worker receives this message by listening to an event, then receives the data, it does whatever you need it to do and returns the result as another message.

In the following example you will see how we can call to the lastfm API in background very easily. The benefits of this approach consist in improving the user experience and the responsiveness of the page which is a very great value.

So here you are the HTML:

</pre>
<!DOCTYPE html>
 <html>
 <head>
 <title></title>
 <meta charset="UTF-8">
 <meta name="author" content="Eugenia Pérez, eugenia_perez@cuatrovientos.es">
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <style>
 .artist{
 float: left;
 width: 200px;
 height: 200px;
 }
 </style>
 <script type="text/javascript">
 var myWorker = new Worker('worker.js');

myWorker.addEventListener("message", function (e) {
 var result = "";

if(typeof(e.data.topartists) !== 'undefined'){
 //Get array of artist coming from the web worker
 var artists = e.data.topartists.artist;

for(var i = 0; i < artists.length; i++){
 result += '<div class="artist"><h3>' + artists[i].name +
 '</h3><img src="' + artists[i].image[2]['#text'] + '"/></div>';
 }
 }else if(typeof(e.data.artist) !== 'undefined'){
 //Get artist info
 var artist = e.data.artist;
 result = '<h2>' + artist.name + '</h2>';
 result += '<img src="' + artist.image[3]['#text'] + '"/>';
 result += '<p>' + artist.bio.summary + '</p>';
 result += '<ul>';

for(var i = 0; i < artist.similar.artist.length; i++){
 result += '<li>' + artist.similar.artist[i].name + '</li>';
 }
 result += '</ul>';
 result += '<p>Más info en <a href="' + artist.url + '">este enlace</a>';
 }
 document.getElementById('result').innerHTML = result;
 }, false);

var getPopularArtists = function(){
 myWorker.postMessage();
 };

var getArtist = function(){
 myWorker.postMessage(document.getElementById('artistName').value);
 };

</script>
 </head>
 <body>
 <div>
 <button onclick="getPopularArtists()">Get popular artists</button>
 </div>
 <div>
 <input type="text" placeholder="Search artist" id="artistName"/>
 <button onclick="getArtist()">Get artist info</button>
 </div>

<div id="result"></div>
 </body>
 </html>
<pre>
</pre>
And the created worker:

var lastfm;

self.addEventListener('message', function(e) {
 /* Create a LastFM object */
 lastfm = new LastFM({
 apiUrl : 'http://ws.audioscrobbler.com/2.0/?method=',
 apiKey : 'f21088bf9097b49ad4e7f487abab981e'
 });

if(typeof(e.data) !== 'undefined'){
 getArtistInfo(e.data);
 }else{
 getTopArtists();
 }
 });

var getArtistInfo = function(artistName) {
 importScripts(lastfm.getApiUrl() + 'artist.getinfo&artist=' + artistName + '&api_key=' +
 lastfm.getApiKey() + '&format=json&callback=sendResponse');

};

var getTopArtists = function() {
 importScripts(lastfm.getApiUrl() + 'tag.gettopartists&tag=disco&api_key=' +
 lastfm.getApiKey() + '&format=json&callback=sendResponse');

};

var sendResponse = function(data){
 postMessage(data);
 }

function LastFM(options){
 /* Set default values for required options. */
 var apiUrl = options.apiUrl || '';
 var apiKey = options.apiKey || '';

this.getApiUrl = function(){
 return apiUrl;
 };

this.getApiKey = function(){
 return apiKey;
 };
 }
<pre>

That’s all forks. Enjoy your coding!

Facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

Leave a Reply

Your email address will not be published.