234mla
Last Updated: February 25, 2016
·
2.059K
· 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'

Say Thanks
Respond

5 Responses
Add your response

13519
0 nfyu8txkcy7l9htqq8v08golvgypn tq96e18gxteze wf5n43u8aci7u1puckp4vxyt753o6cjr

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 ·
13533

@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 ·
13534

@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 ·
13572
357cf38ef2f2799a261b9cc08703f4ef

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 ·
13791
0 nfyu8txkcy7l9htqq8v08golvgypn tq96e18gxteze wf5n43u8aci7u1puckp4vxyt753o6cjr

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 ·