Last Updated: February 25, 2016
·
2.559K
· stowball

Simple way of detecting no SVG support for content and background images

David Bushell and Chris Coyier have both blogged about this little trick for loading a bitmap fallback for an SVG loaded through an <img> tag:

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

By taking it a tiny bit further, we can detect* whether SVG is supported and have a CSS class ready for gracefully degrading SVGs used as background images:

<img src="image.svg" onerror="this.onerror=null; this.src='image.png; document.documentElement.className+=' no-svg'">

This will add a class of no-svg to the <html> tag if the SVG image errors. Any background SVGs defined in your CSS could then be written like so:

.sprite {
    background-image: url(image.svg);
}

.no-svg .sprite {
    background-image: url(image.png);
}

Note: that this will only detect whether the SVG fails to load, which in 99.99% of the time should also correlate to SVG support, and not a network issue.

Only use the this technique on one <img> (such as the logo) so you're not modifying the DOM on every failed image'

5 Responses
Add your response

Why not to use the trick mentioned by Chris Coyier of to use multiple backgrounds support?

body {
  background: url(fallback.png);
  background-image: url(image.svg), none;
}

For your cases, this appears simpler.

over 1 year ago ·

@robsonboral I could but SVG support and multiple background support don't correlate. Android <= 2.3 supports multiple backgrounds, but not SVG for example. I haven't tested it, so I'm not sure what Android <= 2.3 would end up getting

over 1 year ago ·

@robsonboral I could but SVG support and multiple background support don't correlate. Android <= 2.3 supports multiple backgrounds, but not SVG for example. I haven't tested it, so I'm not sure what Android <= 2.3 would end up getting

over 1 year ago ·

I like this option I stumbled accross.

add modernizer.js

add this to your html:


        if(!Modernizr.svg)var i=document.getElementsByTagName("img"),j,y;for(j=i.length;j--;)y=i[j].src,y.match(/svg$/)&&(i[j].src=y.slice(0,-3)+"png")
</pre></code>

Then have your .svg and .png backup file called the same name!
over 1 year ago ·

Take a look at this:

<svg width="96" height="96">
    <image xlink:href="svg.svg" src="svg.png" width="96" height="96"/>
</svg>
over 1 year ago ·