Providing support for older browsers can cause headaches. Here's some handy advice on how to convert SVGs into PNGs with no stress.
SVG to PNG fallback in Grunt
As you’ll have found out SVG’s are not supported in Internet Explorer 8 and below so you need a fallback for support. As this is a tedious task creating two images for every icon/image their needs to be a way of just creating one image with a fallback. Well there is!
First of all you’ll need to download the latest svg2png plugin (assuming you have already have a created grunt file).
Once downloaded you need to load the downloaded plugin:
grunt.loadNpmTasks('grunt-svg2png');
For the SVG fallback you’ll need to create two directories within your images directory, PNG and SVG. The SVG2PNG plugin will now need setting up so the source is pointing to the SVG directory then set the destination to the PNG directory.
svg2png: { all: { files: [ { src: [‘images/svg/**/*.svg'], dest: ‘images/png/' }, ] } }
Next we need to create a default task where the ‘svg2png’ and ‘compass’ tasks can be run automatically if Grunt is executed without specifying any tasks:
grunt.registerTask('default', ['svg2png','compass']);
You’ll also want to add a watch task to both the sass files and images for any changes that are applied:
styles: { files: ['sass/**/*.scss',], tasks: ['compass'], options: { spawn: false, livereload: true }, }, images: { files: ['images/**'] },
To test this is working correctly create a SVG file and add this to you source directory. Run ‘grunt’ within terminal then you’ll notice, as long as this is done successfully, a PNG file will be added to the destination directory replicating the SVG.
Now you should have both images, SVG for supported browsers and a PNG fallback.
For a fallback you can create a mixin and include this to all icons or images where appropriate.
@mixin svg-png($icon) { background: url('../images/png/#{$icon}.png') transparent 0 0 no-repeat; background: none, url('../images/svg/#{$icon}.svg') 0 0 no-repeat; } .icon { @include svg-png('phone'); }
In this instance above I have created an SVG file called ‘phone.svg’ and the PNG has been generated with the same name. This mixing works by including both of the images however the first background style is only applied to Internet Explorer 8 and versions below then the second background style applies to all supported browsers.
The Icon class which has an ‘include’ passes the name of the file, in this case this is ‘phone’ and the mixin pulls through the images within the directories.