It works fine everywhere but not in IE 11 (I have not tested other IE versions yet).
var img = new Image();
img.onload = function(){
alert( 'img: ' + img.width + 'x' + img.height +
' natural: ' + img.naturalWidth + 'x' + img.naturalHeight );
};
img.src = 'http://upload.wikimedia.org/wikipedia/en/b/b5/Boeing-Logo.svg';
JSFiddle: JSFiddle
Result:
img: 121x30 natural: 121x30
- Real browsers (Chrome, Safari, Firefox, ...)
img: 0x0 natural: 0x0
- IE 11
There is a similar question here: Getting image width on image load fails on IE
None of the solutions from those answers work for svg.
Is there a way to get the width and height of a svg file loaded with Image() in Internet Explorer 11?
Note: I am looking for a solution without having to add the element to the DOM for measuring, as I want to avoid any unnecessary re-flow/repaint.
In html5 standard:
If img not rendered then IE reserves the right to display 0. And it seems he is doing this.
With .naturalWidth and .naturalHeight similar situation.
Well, I don't think you can access the SVG content if it is loaded as a
src
attribute, and not inline.One solution might be to change the way the SVG is loaded, so perhaps load via AJAX, and then append to the document by another means. This gives you a chance to have full access the the SVG source before adding to the document...
JSFiddle
This example has used jQuery, and loads the content of the SVG as xml, but you could do it in many ways following the same principle, for example loading as text string, and accessing with regular jQuery methods, or without jQuery at all.
The moral of the story, is that if you load it via AJAX, you can get a reference to the content of the SVG and have more control over it before it gets added to the page.
This code works in IE11:
And yes - this solution is not ideal.