6

I'm using D3.js to render a graph with nodes containing raster images.

var mainscreenURL = s3_base_url + viewController + "/screenshot.jpeg";
svg.select(".mainScreen").transition().attr("height",0).remove();

svg.append("image").attr("xlink:href", mainscreenURL)
        .attr("width", mainScreenW)
        .attr("height", mainScreenH)
        .attr("x", (w / 2) - (mainScreenW / 2)) 
        .attr("y", (h / 2) - (mainScreenH / 2)) 
        .attr("class", "mainScreen")
        .attr("id", viewController)
}); 

Some of these images are pretty large, so the HTTP requests (made implicitly by the browser) can take a substantial amount of time. I can't cache the images, since they're dynamically generated.

If this were regular HTML, I'd show a placeholder image, and then swap it out for the real thing upon successful completion of the HTTP get request. But since this is SVG, there is no explicit request, and I end up with a nasty broken image which is then replaced with the real thing.

Are there any events I can hook to know when the image is fully loaded?

nont
  • 9,322
  • 7
  • 62
  • 82

2 Answers2

3

See related: Is it possible to listen image load event in SVG?

I couldn't get the native addEventListener approach to work, but it looks like you can just set the onload attribute (works in Chrome, at least):

svg.append("image")
    .attr('onload', function() {
         alert('loaded');
    })
    .attr("xlink:href", mainscreenURL);

See fiddle: http://jsfiddle.net/dKxH9/

Community
  • 1
  • 1
nrabinowitz
  • 55,314
  • 10
  • 149
  • 165
  • 2
    interestingly, the image is sometimes already in the browser, so onload doesn't always get called. what are the other events? can you point me to where you found this? (Or did you just guess and try it!?) EDIT: found them here: http://www.w3.org/TR/SVG/interact.html#SVGEvents – nont Sep 17 '13 at 20:31
0

@nrabinowitz, your code doesn't work as it was planned.

Using .attr('onload', function() {}) calls function during assigning 'onload' attribute, not during onload event.

Proper implementation should be as follows (see http://jsfiddle.net/L83nag59/)

svg.append("image")
.on('load', function() {
     alert('loaded');
})
.attr("xlink:href", mainscreenURL)

Unfortunately, it doesn't work in IE11.