Created
January 31, 2019 18:37
-
-
Save thomhines/b3ddfcd14603a90486fd8e3ed114e762 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// inlineSVG | |
// Convert <img> elements pointing to SVG files to inline SVG | |
// | |
// With some help from https://snippetlib.com/jquery/replace_all_svg_images_with_inline_svg | |
jQuery.fn.extend({ | |
inlineSVG: function(callback) { | |
$(this).each(function() { | |
var $img = $(this) | |
var imgAttr = this.attributes | |
if(!$img.attr('src')) return | |
$.get($img.attr('src'), function(data) { | |
// Get the SVG tag, ignore the rest | |
$svg = $(data) | |
for(x = 0; x < imgAttr.length; x++) { | |
if(imgAttr[x].name == 'src') {} | |
// Make new SVG accessible... | |
else if(imgAttr[x].name == 'alt' && imgAttr[x].value) $svg.prepend("<title>"+imgAttr[x].value+"</title>") | |
else if(imgAttr[x].name == 'desc' && imgAttr[x].value) $svg.prepend('<desc id="catDesc">'+imgAttr[x].value+'</desc>') | |
// Add all attributes from img element back to svg element (except the src attribute) | |
else if(imgAttr[x].value) $svg.attr(imgAttr[x].name, imgAttr[x].value) | |
} | |
// Remove any invalid XML tags as per http:validator.w3.org | |
$svg = $svg.removeAttr('xmlns:a'); | |
// Replace image with new SVG | |
$img.replaceWith($svg) | |
if(callback) callback() | |
}, 'text') | |
}) | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment