Using SVG images and fallbacks

SVG is a vector based image format. The advantage of vectors is that images are always sharp, even if you zoom in or are have a high density screen. There are basically 2 methods to include SVGs, either by reference or inline.

The referenced method works just like a regular image by referencing it in an img tag:
<img src="logo.svg" alt="Logo">

SVG is a XML-based format that consists out of plain text. Since HTML5 it is part of the HTML specification. With the inline method you can place the image directly in your HTML code:
<svg>...</svg>

Unfortunately older browsers do not support SVG. So you if you need to support IE8 or old Android / iOS devices you need to use a fallback. Also you need to be aware that there are different SVG versions with a varying support in browsers. Look at the Can I Use SVG page to see which parts are supported.

Below is an overview of available methods. Common methods depend on javascript. In Chrome you now can use srcset, which is intended for responsive images. Other browsers are also expected to implement this.


<img src="logo.svg" onerror="this.src='logo.png';this.onerror=null;">


<img src="logo.svg">
<script>
if (!document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Image", "1.1")) {
  var im = document.getElementsByTagName("img");
  var l = im.length;
  for (var i = 0; i < l; i++) {
    im[i].src = im[i].getAttribute('src').replace(/\.svg$/, '.png');
  }
}
</script>


<img src="logo.png" srcset="logo.svg">

[update] Alexey Ten describes a technique that uses the behaviour of browsers to interpret <image> as <img>


<svg>
<image xlink:href="logo.svg" src="logo.png" />
</svg>

To see the different solutions in action, you can take a look at my SVG fallback demo.