Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I display a placeholder image in my SVG until the real image is loaded?

Tags:

svg

d3.js

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?

like image 791
nont Avatar asked Sep 17 '13 18:09

nont


People also ask

Can a placeholder be an image?

A placeholder image can communicate what type of image is intended to be shown in a particular place, and how it should layout, resize, and flow within the browser.

How do you put a placeholder on a picture?

Whenever you load large image on the page and it's taken too much time, that time you can show loading image or you can say Placeholder image ( Html Image Placeholder ) within the same image tag. You can do this simply by using CSS. Use background property of css and set url of an loading image.

What are placeholder graphics?

In PowerPoint, a placeholder is a pre-formatted container on a slide for content (text, graphics, or video). The pre-set formatting makes it easier to format slides consistently.

Does the browser load hidden images?

So why do browsers load images even when they're hidden? Simply explained: The browsers parses HTML first and as it encounters external resources it will start requesting them.


1 Answers

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/

like image 50
nrabinowitz Avatar answered Oct 01 '22 20:10

nrabinowitz