Created
July 29, 2012 22:01
-
-
Save madrobby/3202087 to your computer and use it in GitHub Desktop.
Fallback to PNG if SVG is not supported
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- example for the http://retinafy.me ebook --> | |
<style> | |
div.rss { | |
background: url(rss.svg); | |
width: 32px; | |
height: 32px; | |
} | |
body.no-svg div.rss { | |
background: url(rss.png); | |
} | |
</style> | |
SVG with PNG fallback:<br> | |
<img data-svg="rss"> | |
<br><br> | |
Background SVG with PNG fallback: | |
<div class="rss"> | |
<script> | |
// This is just an example, and you'll likely need to adapt it.. | |
// | |
// 1) adds a "no-svg" CSS class to <body> if SVG is not supported, | |
// so you can special-case CSS background images | |
// 2) loads all IMG tags that have a "data-svg" attribute set with | |
// either .svg or .png added to the url given in that attribute | |
// | |
// If you create new IMG tags with data-svg on the page later, you'll need to | |
// call the window.updateSVGIMG method. | |
(function(global){ | |
var svg = !!('createElementNS' in document && | |
document.createElementNS('http://www.w3.org/2000/svg','svg').createSVGRect) | |
if (!svg) document.body.className += ' no-svg' | |
;(global.updateSVGIMG = function(){ | |
var i, src, extension = svg ? '.svg' : '.png', | |
elements = document.getElementsByTagName('img') | |
for (i=0;i<elements.length;i++) | |
if (src = elements[i].getAttribute('data-svg')) { | |
elements[i].src = src + extension | |
elements[i].removeAttribute('data-svg') | |
} | |
})() | |
})(this) | |
</script> |
Works really well! The only con about this technique is wrapping the image in an does not link the image. So things like logos, social media icons, etc. won't function.
If you want to avoid Javascript, as an alternative you can use a CSS-only technique I described at http://pauginer.tumblr.com/post/36614680636/invisible-gradient-technique
Another technique, as described here: http://tavmjong.free.fr/SVG/BUTTON_TEST/button_test.html (second code snippet) is to use an error handler on the img. Apparently it even works with IE5.5!
Jacques.
Why not to use Modernizr? maybe you will need it for check others element support. Another way to fallback to .png
using jQuery:
if (!Modernizr.svg) {
$(".rss").css("background-image", "url(rss.png)");
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your solution with img and data-* is a bit awkward, it's better to simply do as follow :
No JS, work everywhere ;)