Skip to content

Instantly share code, notes, and snippets.

@davidcmoulton
Last active August 29, 2015 14:11
Show Gist options
  • Save davidcmoulton/ebb01686e6be80dded9c to your computer and use it in GitHub Desktop.
Save davidcmoulton/ebb01686e6be80dded9c to your computer and use it in GitHub Desktop.
Use Modernizr to load svg or png background images
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<meta charset="UTF-8">
<title>SVG with png fallback</title>
<!-- Modernizr must have svg feature test included! -->
<script src="PATH_TO_MODERNIZR"></script>
<style>
.image {
/* Dimensions for this demo only. */
width: 500px;
height: 500px;
background-size: contain;
background-position: 0 0;
background-repeat: no-repeat;
}
.no-js .image,
.no-svg .image {
background-image: url(images/image.png);
}
.svg .image {
background-image: url(images/image.svg);
}
</style>
</head>
<body>
<h1>I am specimen code for implementing SVG background images with png fallback.</h1>
<p>Please note:</p>
<ul>
<li>Only one image http request is made: no swapping one format in if support requires it, (which is a bad technique as it uses 2 http requests).</li>
<li>Dependancy: Modernizr's feature detection of svg support and use of svg/.no-svg classes. There is no overhead here if you're already using Modernizr. (Considered rolling my own, but feature-detecting SVG with <code>document.implementation.hasFeature</code> seems to have a high false positive problem.)</li>
</ul>
<p>An image specified in the css should load below. SVG if supported, otherwise png.</p>
<div class="image"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment