SVG code within HTML versus SVG embedded with <img> tag
Asked Answered
H

1

5

Is there a technical (dis)advantage to including SVG-code in a HTML-file versus embedding it with an <img> tag?

I'm not asking about personal preference or opinion, but factual differences on the technical level.

Browser compatibility would be an example. Caniuse.com tells me there is virtually no difference in that respect (SVG as img vs inline SVG code). But maybe there are other factors that I'm not aware of?

SVG as part of the HTML code:

<html>
...
<body>
    ...
    <svg version="1.1" ... >
        ...
    </svg>
    ...
</body>
</html>

SVG embedded as image:

<html>
...
<body>
    ...
    <img src="image.svg" ... >
    ...
</body>
</html>
Huntlee answered 20/3, 2021 at 10:3 Comment(4)
On the one hand you can't use SVG fragment identifiers unless the file is external. On the other hand you can't actively change an SVG if it's not internal. Just two examples from the top of my head.Trachoma
What happens when there's a change to the image formats used? In the first, you get to go write css again, since you no longer have SVG elements for pictures. In the second, you just change the extension of the image source. But then, you've generated 2 requests instead of one - for everyone. Was the site likely to change? No? Then you've done more work to make potential future maintenance easier, at the expense of an extra request.Shackle
I believe when an svg uses external files like fonts or bitmaps it doesn't work when used as an <img> for security reasons. On the other hand it's easier to resize when used as <img> using css, from what I remember.Devora
Does this answer your question? Inline SVG vs SVG File PerformanceNankeen
C
1

One significant advantage of using the <svg /> tag over the <img /> tag is the ability to modify the CSS and properties of the <svg /> tag's child elements synchronously. For instance, hiding an element within the SVG is not possible when using the <img /> tag. Additionally, setting the color property to currentColor does not work with the <img /> tag. I hope this will be helpful to users. Thx

Colloquy answered 19/7 at 2:36 Comment(1)
Having them inline for things like current color is very helpful. Using <use> is helpful to reduce clutter, but you still need to load the SVG inline somewhere. For icons and stuff I'd say the img tag is easier, but you'd need to make sure the colors are hard coded. +1Bifrost

© 2022 - 2024 — McMap. All rights reserved.