Creating SVG icons with PNG fallbacks

| 3 min. (477 words)

Images suck at being responsive. This combined with the ever increasing PPI(pixels per inch) of our laptops/phones (soon desktop monitors) means designing for 72dpi is no longer really a sustainable solution. If your image is originally derived from vector artwork, you have the option to save it as an SVG (Scalable Vector Graphic).

SVG’s scale indefinitely, and are widely supportedIn this post I’m going to show you how to go about creating SVG icons that scale with PNG fallbacks to make your life a whole lot easier!

Why would you use SVG?

Well.. you COULD send a larger, more detailed PNG/JPG with more than twice as many pixels to a HiDPI device (most likely a mobile phone), to show a crisp image, but that means that your user is going to be downloading that larger image, most likely on their phone on a slow internet connection. Spending precious seconds loading the image, all whilst burning bandwidth downloading all those bitmapped pixels. That’s pretty lame!

Another cool thing is that most browsers ONLY download the used image, so you’ll only be sending one image, saving precious bytes of mobile data.

The Pros:

  • Simple SVGs usually have a SMALLER file-size than equivalent PNGs
  • Faster load times vs large PNGs
  • Works in all modern browsers
  • Scalable to ANY screen size (“Retina ready”)
  • Solid fallback: users on unsupported browsers will get scaled up PNGs

The Cons:

  • This method only works on background images (You’ll need Javascript to detect and replace images if they are inline)

Prerequisites:

  • A vector graphic

So how do we do this…

Step one: Saving out a SVG and PNG

  • Open up your vector graphic in Adobe Illustrator (or equivalent)
  • I design at a 72 ppi to avoid image scaling problems. (scaling up is easy!)
  • Save image out as a PNG(24bit) and SVG

Step two: Including Modernizer

Simply include Modernizer.js in the head of your project, Modernizer adds classes to the html element if a new web technology is available. e.g: if SVGs are available Modernizer will output the class html.svg on the html element.

Step three: HTML & CSS

Create an element, set png as a background-image, specify the element size, then replace the PNG with SVG using Modernizer.

.my-image {
  background-image: url('image.png');
  background-size: imgHeight imgWidth;
}
// if browser is SVG-able
html.svg {
 .my-image {
   background-image: url('image.svg');
 }
}

Step four: Profit

All done. Now your image will be looking crisp on any device, at any zoom level, all the time for a fraction of the file size! I hope you found this tutorial useful, give it a try with the code-snippets below. If you’re a developer, or work with a development team, be sure to give Raygun a try whilst you’re here. There’s a free trial, so signup and invite your team to see how you can discover and identify software errors in real-time!