Skip to content

Instantly share code, notes, and snippets.

@yemster
Created October 20, 2016 11:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yemster/72f249307a5e8b217158e5077f566dc4 to your computer and use it in GitHub Desktop.
Save yemster/72f249307a5e8b217158e5077f566dc4 to your computer and use it in GitHub Desktop.
SVG IMG replacer: Replace a given IMG linking to an SVG file with the actual SVG file injected into the page.
// Extract and inject SVG logo into document
$(document).ready(function() {
$('img[src*=".svg"]').each(function() {
var $img = jQuery(this), $svg,
imgURL = $img.attr('src').replace(/\.svg(\?\w+)/,'.svg'), // strip timestaps from img URL
imgAttributes = $img.prop("attributes");
$.get(imgURL, function(data) {
$svg = jQuery(data).find('svg'); // Get the SVG tag, ignore the rest
$svg = $svg.removeAttr('xmlns:a'); // Remove any invalid XML tags
// Append orig IMG attributes to the SVG
$.each(imgAttributes, function() {
if (this.name !== 'src') $svg.attr(this.name, this.value);
});
$img.replaceWith($svg); // Replace IMG with SVG
}, 'xml');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment