SVG fallback

There are still a few browsers that don't support SVGs so it is good practice to provide a proper fall back option. One technique to do this is to utilize the img tag onerror event. Lets say that your site uses all SVGs and if someone makes a request to your site with a browser that doesn't support SVGs this event is fired when an error occurs loading the image. Your HTML might look something like this:

<img src="/assets/images/logo-gray.svg" onerror="this.src=/assets/images/logo-gray.png">

Automate conversion of SVGs

The next process is converting all of your svg images to a png. You could use the Apache Batik Project which has good transcoding support for images and tie it into your maven build process or create a one off program to run. I prefer to automate the process so developers don't have to remember to run it is the way to go.

If you aren't tied to java an alternative way would be to incorporate it in the front end developer process. Using grunt.js, a JavaScript task runner, and a grunt plugin grunt-svg2png you can rasterize SVG to PNG images. When your production tasks run you can make a call to convert the svgs to pngs. Using this plugin, it looks something like:

svg2png: {
    files: [
        {
            cwd: "src/assets/images/",
            src: ["**/*.svg"],
            dest: "output/assets/images/"
        }
    ]
}

Automate adding the onerror event

If are dealing with a site with lots of images or various types of images you might want to be lazy and create a way to automate adding the onerror to reference to the fallback image. This will prevent developers having to remember the direcotry or image naming standards you set up, plus it will save a little typing which we all like.

Using grunt-text-replace we will use a regex to look for image tag containing svg in the html files and replacing the last > with the onerror snippet.

replace: {
    your-target: {
        ...
        replacements: [{
            from: /<img\s+[^>]*src="([^"]*.svg)[^>]*>/g,
            to: function(matchedWord) {
                return matchedWord.replace(">", " onerror=\"this.src=" + regexMatches[0].replace(".svg", ".png") + "\">");
            }
        }]
    },
}