Is it possible to listen for an <image>
load event in SVG? If yes, how to do this?
SVG is XML based, which means that every element is available within the SVG DOM. You can attach JavaScript event handlers for an element.
The load event fires on an SVGElement when it is loaded in the browser, e.g. in the DOM in the case of an embedded <svg> . It is basically the same as the standard load DOM event.
<image> The <image> SVG element includes images inside SVG documents. It can display raster image files or other SVG files. The only image formats SVG software must support are JPEG, PNG, and other SVG files.
The onload event occurs when an object has been loaded. onload is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).
Yes it's possible.
In markup:
<image xlink:href="example.png" width="10" height="10"
onload="alert('loaded')"/>
See jsfiddle.
In script:
<script>
var img = document.createElementNS("http://www.w3.org/2000/svg", "image");
img.addEventListener('load', function() { alert('loaded'); });
// or alternatively:
// img.onload = function() { alert('loaded'); }
img.width.baseVal.value = 100;
img.height.baseVal.value = 100;
img.href.baseVal = "example.png";
</script>
See jsfiddle.
I found that this would not work for SVG object created using D3, but the answer here worked great:
How can I display a placeholder image in my SVG until the real image is loaded?
For example this worked:
var img = innerG.append("image")
.attr('onload', function() {
console.log('loaded');
})
.attr("xlink:href", src)
.attr("width", size)
.attr("height", size);
But this did not work:
var img = innerG.append("image")
.attr("xlink:href", src)
.attr("width", size)
.attr("height", size);
img.addEventListener('load', function() { console.log('loaded'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With