2
votes

I've just read this article from Google Web Fundamentals on using SVG for icons. Two approaches are given. The first is the inline approach. For example:

  <svg version="1.1" xmlns="http://www.w3.org/2000/svg"
       xmlns:xlink="http://www.w3.org/1999/xlink"
       width="32" height="32" viewBox="0 0 32 32">
    <path d="M27 4l-15 15-7-7-5 5 12 12 20-20z" fill="#000000"></path>
  </svg>

Demo

The second approach is to use an image tag such as: <img src="credit.svg">

I'm also aware SVGs can be defined as:

  • an object
  • an embed tag
  • an iframe

They can also be set as background images in CSS.

My question:

What are the advantages and disadvantages of each approach?

3

3 Answers

3
votes

The advantages of using img, object, embed and other with SVG backgound:

  • <img class="icon icon_foo"> is much shorter and beautiful than inline SVG — <svg class="icon icon_foo"><use xlink:href="#foo"></use></svg>

The disadvantages of using img, object, embed and other with SVG backgound:

  • you absolutely have no any control of styling options — you cannot set color, outline width and outline color — all you can do is just to put SVG as background and set styles right in SVG file one time
  • you cannot reuse your icons because of statement above (if you have one icon in two-three-twenty different places on your web page and it should be colored in different colors the only way is to create two-three-twenty equal SVG files with only one difference — fill option ;)

The advantages of using inline SVG:

  • reusability (eg. you have only one Twitter SVG icon and you can use it everywhere with any styles, so, you do not need 2 or 3 same SVG files just with different fill attribute in each SVG file)
  • complete control over your icon appearance — styles, colors, sizes

The disadvantages of using inline SVG:

  • it is longer than IMG and does not look beautiful

Caching:

Using AngularJS or any other framework:

<ng-include src="'icons.html'"></ng-include>

Using VanillaJS:

file icons.js on your server:

var icons = '<svg><symbol id="icon-XXX" viewBox="0 0 256 256"><path d="{here_goes_compounded_path}"></path></symbol></svg>';

in HEAD section:

<script src="icons.js"></script>

<script>
    document.getElementById('icon-placeholder').innerHTML(icons);
</script>

right after the BODY tag:

<div id="icon-placeholder" style="display:none;"></div>

Fiddle with the best approach:

Right after body tag place all your SVG icons (or use Angular's or any other framework ng-include):

<body>
    <svg style="display:none;">
        <symbol id="icon-XXX" viewBox="0 0 256 256"><path d="{here_goes_compounded_path}"></path></symbol>
        <symbol id="icon-YYY" viewBox="0 0 256 256"><path d="{here_goes_compounded_path}"></path></symbol>
    </svg>

In any place on your web page put an icon:

<svg class="icon icon_red">
    <use xlink:href="#icon-XXX"></use>
</svg>
<svg class="icon icon_green">
    <use xlink:href="#icon-YYY"></use>
</svg>
<svg class="icon icon_blue">
    <use xlink:href="#icon-XXX"></use>
</svg>

In CSS:

.icon {
    width: 16px;
    height: 16px;
    fill: currentColor;
}
.icon_red { fill: #f00; }
.icon_green { fill: #0f0; }
.icon_blue { fill: #00f; }

.icon_foo {
    stroke: #000;
    stroke-width: 8;
    fill: #0f0;
}

Do not forget about magic "currentColor" CSS variable — it will color your SVG icon in current text color:

fill: currentColor;

Further must read:

1
votes

The answer is, should you be worrying about who's looking at your code? SVG inline will always bloat your HTML depending how complex the drawn SVG is. Inline does in some respect have better performance implications due to the fact it's being loaded directly with the HTML as opposed to loading the SVG externally when using it, for example, as an <img>. However, it's practically unnoticeable and should be the least priority when coming down to performance.

The disadvantages of inline SVG:

  • Bloats code
  • Cannot be cached by the browser
  • No fallback available
  • IE, without XHTML (and that's if SVG is supported) doesn't support SVG technically, though this is a low priority and we shouldn't care about it in the current world of the web. Still, it's primarily a disadvantage to those ancient warriors.

The advantages of inline SVG:

  • I can't think of any, seriously. Other nosey people can see it?
  • Actually, those without CSS enabled can see it.

The disadvantages of using <img> with SVG:

  • Again, limited fallback support (You can use Modernizr to replace the .svg extension with .png, but then you rely on the user having javascript enabled)
  • Limited styling options with the SVG

The advantages of using <img> with SVG:

  • Semantically better than bloating all your code
  • Readability in your codebase is better for a) yourself and b) other developers who might be working on the project too.
  • Better maintainability.

Alternative methods:

You can use the following methods you provided in your question (and below) about using <object>, <embed> and <iframe>, although, these also limit the use cases and would need declaring in every HTML document, which can get messy as you progress in a project, whether it be large or small.

The 'better approach':

Disclaimer: By no means is the a 'better for everyone' method. This is simply how I would declare my SVG elements for reusability and gives me full control of identifying my assets when using SVG.

The biggest pitfall for using inline SVG in your HTML is the fallback support. I have always used SVG as a background image (unless it's a webfont I'm using for icons etc.), purely because I can create a .png version and write the fallback in my CSS, like so:

.icon {
    display: inline-block;
    vertical-align: baseline;
    background-repeat: no-repeat;
    background-position: center center;
    background-size: contain;
}

.icon--16 {
    width: 16px;
    height: 16px;
}

/* Always declare the PNG before the SVG. */
.icon--foo-blue {
    background-image: url('foo-blue.png'); /* Fallback */
    background-image: url('foo-blue.svg'), none; /* Modern */
}

.icon--foo-green {
    background-image: url('foo-green.png'); /* Fallback */
    background-image: url('foo-green.svg'), none; /* Modern */
}

Then, use it:

<span class="icon icon--16 icon--foo-blue"></span>
<span class="icon icon--16 icon--foo-green"></span>

The disadvantage of this:

  • No support for CSS styling, however, we should be aware of why we are styling SVG in our CSS. If you're using more colours than your website uses then there is generally something not right. Declaring 4 files for the same SVG but in a different colour is not bad practise as it allows us to cache these in the browser for later, throughout any webpage which in the answer constructed below completely removes this purpose. Take advantage of caching on the server/within the browser!

And of course, it depends what kind of image you are trying to render to the user. If you're going to use large SVG files for showcasing something, for example, I would probably think about what kind of users I'm targeting; that being, those on modern browsers because I might want to include fancy inline SVG animations etc.

It really depends on personal preference too. There is no major red flags for using SVG inline to this day, but we still have some heart for those back in the stone ages of less-than IE9. And, not to forget, Android is quirky with SVG too!

EDIT: It seems like there is a large debate over inline SVG's. One word of warning is, there is no reusability doing this. If you're showcasing a fancy website with fancy SVG animations, then by all means, build your entire page in SVG for crying out loud. No one is stopping you. It's personal preference. But for icons, where you will more than likely reuse throughout a project, please, declare them outside your HTML as it gives you greater control in the long run and not because you need a different colour here and there. Think about it. :)

1
votes

What I tend to do nowadays is wrap it inside a Web Component:

/assets/svg/hex.js

export default `<svg>...</svg>`;

/my-svg.js

class MySvg extends HTMLElement {
  connectedCallback() {
    const id = this.getAttribute('id');
    import(`./assets/svg/${id}.js`).then(svg => {
      this.innerHTML = `
        ${svg.default}
      `;
    });
  }
}
customElements.define("my-svg", MySvg);

index.html

<my-svg id="hex"></my-svg>

This way I get the advantages of inline svg, lazy loading due to dynamic import and without the bloat in the code I'm supposed to work on / maintain, with just one custom element. And the id attribute makes clear which svg I'm loading.