Skip to content

Fallback solutions

waruyama edited this page Dec 10, 2018 · 1 revision

Fallback solutions for older Browsers

Below you can find fallback solutions for old browsers that do not support SVG and/or Javascript. Note that a fallback for browsers with SVG support that have Javascript disabled is automatically available, because in these cases the <img> element with the SVG will be displayed.

Fallback for no SVG support (IE 7/8)

This example shows how to add a fallback for browsers not supporting SVGs. For these browsers an alternative PNG image source is used to display the image. Browsers that do not support SVG invoke the onerror event handler, because the SVG is not recognized as a valid image. The fallback calls SVGInject.err() in the onerror event handler with the alternative image source as the second argument.

<html>
<head>
  <script src="svg-inject.min.js"></script>
</head>
<body>
  <img src="image.svg" onload="SVGInject(this)" onerror="SVGInject.err(this, 'image.png')" />
</body>
</html>

Another, more generic way of providing a fallback image source is using the onFail hook. If loading the SVG fails, this will try to load a file with the same name except “png” instead of “svg” for the file ending. As an example, if the browser does not support SVG and the src attribute is set to "image1.svg", this will replace the src attribute with "image1.png" .

<html>
<head>
  <script src="svg-inject.min.js"></script>

  <!-- optional PNG fallback if SVG is not supported (IE <= 8) -->
  <script>
    SVGInject.setOptions({
      onFail: function(img, status) {
        if (status == 'SVG_NOT_SUPPORTED') {
          img.src = img.src.slice(0, -4) + ".png";
        }
      }
    });
  </script>
</head>
<body>
  <!-- the onerror="SVGInject.err(this)" is needed to trigger the onFail callback -->
  <img src="image.svg" onload="SVGInject(this)" onerror="SVGInject.err(this)" />
</body>
</html>

Fallback for no SVG and no Javascript support

This will display an image on every browser, even if neither SVG nor Javscript is supported.

If Javascript is disabled or if the browser does not support SVG, the PNG or the SVG will be displayed in an <img> element, depending on whether srcset is supported by the browser. Browsers without SVG support never support the srcset attribute, therefore the PNG will be displayed. If Javascript is enabled and SVG is supported, the beforeLoad function will make sure that the url in the srcset attribute will be used to load the SVG.

This fallback has the disadvantage that on Internet Explorer 9-11 more network traffic will occur, because both the PNG and the SVG will be loaded.

<html>
<head>
  <script src="svg-inject.min.js"></script>
  <script>
    SVGInject.setOptions({
      beforeLoad: function(img) {
        return img.getAttribute('srcset');
      }
    });
  </script>
</head>
<body>
  <img src="image.png" srcset="image.svg" width="128" height="128" onload="SVGInject(this)" />
</body>
</html>