Setting up SVG Fallback Images in WordPress

SVG images are almost 96% supported in browsers but need a bit of backward compatibility for the 4% of stragglers, out of the box WordPress does not support the upload of SVG images via the media loader but you can circumnavigate that by adding the image format to the list of allowed types.

There is a nice javascript plugin called SVGeezy (love that name) that can check if a browser supports SVG and if it doesn’t can fall back to an alternative image in the same directory with a different file type such as .png

Download the latest version of SVGeezy and grab the svgeezy.min.js file and add to your theme’s js folder and enqueue it, also create an init file, here called svgeezy-init.js

<?php //<~ don't add me in
//* Loads SVG fallbacks
add_action( 'wp_enqueue_scripts', 'svgeezy_enqueue_scripts' );
function svgeezy_enqueue_scripts() {
wp_enqueue_script( 'svgeezy', get_bloginfo( 'stylesheet_directory' ) . '/js/svgeezy.min.js', array(), '1.0.0', true );
wp_enqueue_script( 'svgeezy-init', get_bloginfo( 'stylesheet_directory' ) . '/js/svgeezy-init.js', array('svgeezy'), '1.0.0', true );
}
view raw svg-fallback.php hosted with ❤ by GitHub

In the svgeezy-init.js add the below

svgeezy.init(false, 'png');

What we are saying here is to check images and if SVG is not supported use a .png variation in the same location. Accordingly you can use another format like .jpg

You can also filter which images to check by using a CSS class on the image like so

svgeezy.init('nocheck', 'png'); // this will tell the plugin to not check images with a class of 'nocheck'

That’s it, the scripts are set to appear at the bottom of the page, there is no jQuery dependency and the file size is light at 1KB.

 

Leave a Comment





%d bloggers like this: