Last Updated: September 06, 2016
· tombek

Fallback SVG to PNG in img element

At my company, we love to work with svg, but it's not compatible with old browsers like IE8 and inferiors (source). So, here is a good fallback using Modernizr SVG option

First, load modernizr in the head of your document.

Next, copy this code just before the end of document's body :

// Check if browser can handle SVG
    // Get all img tag of the document and create variables
    var i=document.getElementsByTagName("img"),j,y;

    // For each img tag
    for(j = i.length ; j-- ; ){
        y = i[j].src
        // If filenames ends with SVG
        if( y.match(/svg$/) ){
            // Replace "svg" by "png"
            i[j].src = y.slice(0,-3) + 'png'

At last, create a png version of each svg image you have in your page at the same location as svg files.

Here is a condensed version (143bytes)

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")
Say Thanks

4 Responses
Add your response


if the fallback was CSS only, I would consider start using SVG.

over 1 year ago ·

Just yesterday I was trying to achieve this in Rails, with a SVG or PNG in a link. I ended up using one of the last two options suggested here: http://www.webdesign.org/html-and-css/tutorials/ways-to-embed-a-clickable-svg-logo-into-your-website.21984.html

over 1 year ago ·
9k5x00vzrj5g6ulfpvf4 normal

The minified code is missing the brackets from the Modernizr.SVG check, so the for statement is being run regardless.

over 1 year ago ·
9k5x00vzrj5g6ulfpvf4 normal

There is also a semi-colon missing in the first line of the for statement - here is fixed minified code:

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

over 1 year ago ·