3

I'm using mbostock queue.js script to load several json files, by doing something like that:

var q = queue()
.defer(d3.json, "world-110m.json")
.defer(d3.tsv, "world-country-names.tsv")
.await(ready);

where ready is the function to execute when everythin is loaded.

I would like to preload an image by adding a defer. Is this possible? I have tried it several ways, but it doesn't work.

I suppose that a function must be created, but I can't make it asynchronous, and the queue keeps waiting forever...

Vikash Chauhan
  • 792
  • 2
  • 9
  • 18
Roger Veciana
  • 983
  • 1
  • 12
  • 25
  • You mention some code you've tried. Can you post one or more of these? Also explain more background on why you're integrating images into queue.js vs. using some of the existing approaches for image preloading. – explunit Aug 06 '13 at 14:15
  • I tried something like .defer(myFunc, "myImg.png"); where myFunc = function(src){var img = new Image(); img.src = src; img.onload = function(){return true;} }. And some variations. The code is executed, but it's like I don't send the proper signal to await() – Roger Veciana Aug 06 '13 at 15:33

1 Answers1

4

Here is what queue.js is expecting from the callbacks:

The callbacks follow the Node.js convention where the first argument is an optional error object and the second argument is the result of the task.

Thus a simple version of your code might look like this:

var loadImage = function(src, cb) {
    var img = new Image();
    img.src = src;
    img.onload  = function(){ cb(null, img); };
    img.onerror = function(){ cb('IMAGE ERROR', null); };
};

queue()
    .defer(d3.json, "data/flare.json")
    .defer(d3.csv, "data/test.csv")
    .defer(loadImage, "img/test.png")
    .await( function(error, jsondata, csvdata, imagedata) {
        if (error) { console.log('error', error); } 
        else { console.log('success', jsondata, csvdata, imagedata) }
    });

I'm not sure what (if anything) you wanted to return about the image, but in the above example cb(null, img) I'm returning the whole object.

Hugolpz
  • 17,296
  • 26
  • 100
  • 187
explunit
  • 18,967
  • 6
  • 69
  • 94
  • It worked very well, thank you. About the error handling, I understand that I shoul add it like cd(error, img), and then change the function behaviour if error is not null. But I don't know how to detect if the image doesn't load (if the url is wrong, for instance). I know that I can add an img.onerror, but the onload function doesn't seem to get the error value. – Roger Veciana Aug 07 '13 at 08:07
  • 1
    @RogerVeciana see edited version of the code above that adds simple error handling. – explunit Aug 07 '13 at 12:43