Skip to content

Instantly share code, notes, and snippets.

@tomsarduy
Last active September 21, 2016 20:22
Show Gist options
  • Save tomsarduy/c55257e2f4cf16372b58 to your computer and use it in GitHub Desktop.
Save tomsarduy/c55257e2f4cf16372b58 to your computer and use it in GitHub Desktop.
SVG background image with fallback to PNG via jQuery and CSS, with Modernizr library.
Via jQuery:
if (!Modernizr.svg) {
$("#logo").css("background-image", "url(fallback.png)");
}
Via CSS:
#logo {
background: url(logo.svg); //svg by default
width: 32px;
height: 32px;
}
.no-svg #logo {
background: url(logo.png);
}
#Notes:
1. Download a version of Modernizr that is trimmed down to just testing SVG (assuming that’s the only test you need).
2. SVG is a perfect use case for Modernizr, because there is no simple native way to provide a fallback.
3. put Modernizr in your `<head>`, so the class will be added before the default styles are applied and modern browsers won’t download both images
#For the record:
1. The only reason you would need a fallback for SVG these days if you have to support IE 8 and down, or older Android.
2. Yes, it's possible to do this without Modernizr (https://gist.github.com/3202087)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment