Last Updated: February 25, 2016
·
6.633K
· jamesmartin

Embedding SVG with Javascript

Some time ago, I wrote about embedding and styling SVG documents in Rails. That humble snippet of Ruby has since become a full-fledged Rails helper gem (inline_svg), which knows about the Asset Pipeline and can be extended with custom SVG transformations.

One thing inline_svg can't do is embed SVG documents from remote URLs. So I made a little Javascript module (ES6!) to do just that. It's called RemoteSvg and it got its first real usable release (v0.1.0) recently.

Here's a really quick demonstration of the library in action.

Our HTML:

<!doctype html>
<script src="jspm_packages/system.js"></script>
<script src="config.js"></script>
<script>
  System.import('lib/main');
</script>

<body>
  <div id='my-svg' data-remote-svg-uri='/my-doc.svg' data-remote-svg-class='little-red'></div>
</body>

lib/main.js:

import './style.css!';
import {RemoteSvg} from 'remote-svg';

new RemoteSvg(document.getElementById('my-svg'))
.then(function() { console.log('SVG loaded...'); })
.catch(function(err) { console.log('Something went wrong: ' + err); });

lib/style.css:

.little-red {
  width: 5em;
  height: 5em;
  fill: red;
}

And the resulting, transformed SVG, loaded asynchronously from a remote URL:

<svg id='my-svg' class='little-red'>
  <!-- svg data ... -->
</svg>

If you need to load SVGs from remote URLs, or just want to embed and style SVGs in the browser, check out RemoteSvg.