svg.icon.js
Generate accessible markup for use with SVG icon sheets in JavaScript. Use it to inject SVG icons into user interface elements. See also: Roll your own SVG sprite sheets with Bower and Gulp.
This script offers feature parity with the ubik_svg_icon() function in Ubik SVG Icons. It was originally designed for use with those "hard to reach places" (e.g. WordPress core functions that output user interface elements without using apply_filters) but can be used anywhere else you'd like to inject SVG icon markup.
This script has a tiny footprint (less than 1 Kb minified) and no dependencies.
Installation
Bower
bower install svg.icon.js -D
npm
npm install svg.icon.js --save-dev
Usage
svgIcon( [icon], [title], [desc], [css(string|array)], [url] )
Returns SVG icon markup with use syntax. Only icon is required. This should match the ID of an icon in an in-line SVG file or an external SVG file specified in url or the svgIconsUrl global variable. Both title and desc are optional; these fill the appropriate elements and allow for the addition of some WAI-ARIA attributes for greater accessibility. css is either an array of strings (each of which will be added to the default classes) or a string (that will completely overwrite the default classes).
jQuery
Use this however you would usually insert markup e.g. $(element).prepend( svgIcon( [icon] ) );.
WordPress
Provision svg.icon.js with an external SVG icon sheet URL with wp_localize_script (wrapped in a function hooked to wp_enqueue_scripts, for example):
wp_localize_script( [script handle], 'svgIconsUrl', [url] );
Example
This is the sort of markup this script will output:
<svg class="icon icon-awe icon-awe-caret-down" role="img"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://www.example.com/img/icons.svg#awe-caret-down"></use></svg>
License
MIT/GPLv3.