SVG with PNG fallback

SVG is a very good way of presenting images, however not all browsers support it. Browsers that do not support it would simply show nothing!

In order to be able to use SVG images both as <img> html tags and as css background images, we can use PNG fallbacks for older browsers that do not support SVG.

On the internet, a lot say that a simple onerror attribute in the <img> would suffice, however this did not work for me. The modernizer makes it very easy to have html element fallbacks using javascript.

If you do not already have modernizer installed, download here.

Once you add the reference to the modernizer and placed all your <img src=”image.svg” /> tags, place the following code at the bottom of you page in a javascript tag, preferably in document ready :


<script type="text/javascript">


if (!Modernizr.svg) {
var imgs = document.getElementsByTagName('img');
var svgExtension = /.*\.svg$/
var l = imgs.length;
for(var i = 0; i < l; i++) {
if(imgs[i].src.match(svgExtension)) {
imgs[i].src = imgs[i].src.slice(0, -3) + 'png';
console.log(imgs[i].src);
}
}
</script>

Moreover, when using background images a very simple css change should be enough. Instead of using background or background-image, we will use them both. This would set the png first and if SVG is supported, it will be set after the png.


#myImage {
background: url("myImage.png") no-repeat 0 0;
background-image: url("myImage.svg");
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s