0
votes

I'm building a WordPress theme which has an options panel. Within the options panel, admin can upload an icon which will appear in the footer.

When uploading an icon, admin will upload a SVG and PNG version to the media uploader (icon.svg and icon.png for example).

I'm displaying this icon on the front end like so:

<nav>
<?php if( have_rows('footer_icons', 'option') ): ?>
    <ul>
    <?php while( have_rows('footer_icons', 'option') ): the_row();
        // Vars
        $icon = get_sub_field('icon');
    ?>
        <li>
            <img src="<?php echo esc_url($icon); ?>" alt="icon" width="60" height="60">
        </li>
    <?php endwhile; ?>
    </ul>
<?php endif; ?>
</nav>

Is there a way to feature detect and display an inline png fallback (icon.png) should the browser not support SVG? I know Modernizr offers SVG detection, but I couldn't see that it would offer this level of support.

2
Have you tried using modernizr? Should be as simple as checking for support and swapping the src attribute.apaul

2 Answers

1
votes

I would question whether it's necessary at all. Browser support for SVG use in img tags is over 96% globally. Source: http://caniuse.com/#feat=svg-img

If absolutely necessary add the PNG URL as a data attribute to the img tag with the source set to the SVG file. Load in Modernizr and use its feature detection to replace the image's source with the PNG URL if SVG images aren't supported.

Example markup (assumes $png_icon has been set):

<img src="<?php echo esc_url( $icon ); ?>" data-png-src="<?php echo esc_url( $png_icon ); ?>" alt="icon" width="60" height="60">

Further reading:

https://modernizr.com/docs

http://callmenick.com/post/svg-fallback-with-png (Example #4)

1
votes

Since you do display the svg in an <img> tag and not inline as the question's title suggested, the easiest way is to use the onerror event handler :

<img src="https://dl.dropboxusercontent.com/s/b7qcju9ubmdtigj/ball.svg" 
	onerror="this.src='https://dl.dropboxusercontent.com/s/gd7vo53yfrmaqx4/ball.png'"/>