patric-boehner
3/2/2016 - 8:05 AM

Inline SVG with fallback

Inline SVG with fallback

// # SVG Fallback
//**********************************************

.svg-fallback-text
   border: 0
   clip: rect(0 0 0 0)
   height: 1px
   margin: -1px
   overflow: hidden
   padding: 0
   position: absolute
   width: 1px

html.no-svg
   .icon-facebook
      background: url(images/png/facebook.png) no-repeat
      background-size: 16px 28px
      // width: 16px
      // height: 28px
      display: inline-block
      background-position: bottom left
<? php

//* SVG Detect for fallback
//**********************

add_action( 'wp_head', 'pb_svg_detect_script', 1);
function pb_svg_detect_script() {
   $output = "<script type='text/javascript'>!function () {
      function supportsSVG() { return !!document.createElementNS && !! document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect }
      if (supportsSVG()) document.documentElement.className += 'svg'
      else document.documentElement.className += 'no-svg'
   }()</script>";
   echo '<!--SVG Detect-->';
   echo $output;
}

//* SVG PHP output
//**********************
// https://css-tricks.com/a-complete-guide-to-svg-fallbacks/

add_action( 'genesis_after', 'pb_svg_test' );
function pb_svg_test(){
   //* Including SVG files
   $svg = file_get_contents( get_stylesheet_directory_uri() . '/images/svg/facebook.svg' );
   echo '<span class="icon-facebook">'.$svg.'';
   echo '<span class="svg-fallback-text">Follow us on Facebook</span>';
   echo '</span>';
}

#Inline SVG handled via PHP with png background image fallback

In looking at all the methods for implementing svg with fallback I just wanted to make note of this method. I'm not sure if i will ultimately use it but i wanted to make note of it so i can revisit.

Their are multiple ways of adding your svg files. For the purposes of my testing i was interested in directly inlining the svg. I was interested in a way of adding the svg that reduced requests and allowed for direct manipulation of the svg file through css. Plus i could have php do all the work using file_get_contents().

The inline <svg> image is wraped in a <span> element with a class that we can use to target for the .png background-image fallback. This allso adds some additional support for older browsers that wont render the <svg> element at all. I'm using a little bit of JS from Todd Motto to ditect if SVG is supported and return a class of .svg or .no-svg to the html element. When .no-svg is present the background image is applied and the png takes the place of the svg file.

That svg support script needs to be added before any of the css files in the head.

But frankly if your not bothered with supporting anything bellow EI9 then i might just go with mutliple background images instead. I loose the ability to manuipulate the svg via css but i'm not sure if thats a deal breaker.

Refrance & Notes