Reputation: 1461
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.
Upvotes: 0
Views: 404
Reputation: 137084
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'"/>
Upvotes: 1
Reputation: 19318
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:
http://callmenick.com/post/svg-fallback-with-png (Example #4)
Upvotes: 1