Inline SVG

Okay, I’m currently ripsnort delighted to have found a solution to this problem of rendering SVG element dynamically. As in:

  1. My web apps receive some <svg>...<svg> from an Ajax call
  2. ???
  3. Super, there’s a drawing on the page!!!

What is the secret sauce in step 2?

After a merry frolic through the majority of the internets and a dozen prototypes, I finally found the answer. In essence, you just create an “object” element with type and data settings:

javascript

  1. var svgObject = document.createElement('object');
  2. svgObject.setAttribute('type', 'image/svg+xml');
  3. svgObject.setAttribute('data', 'data:image/svg+xml,'+ svgCode); // the "<svg>...</svg>" returned from Ajax call
  4. $("#reportSVGDiv").append(svgObject);

It works in Firefox, and the article explains how to get it working in IE too, which I don’t need just yet.

A few other things I learned and tried:

  • I initially, naievely, tried just adding the SVG via innerHTML. As Jeremy explained to me, this doesn’t work because the browser uses a different compiler for HTML compared to pure XHTML. (And TiddlyWiki, like most things on the web, is HTML.) Even with an <object> tag around it, it won’t just switch over.
  • The easiest way to do this is to use a .svg suffix (or probably set mime type to svg, but this is tiddlywiki and I’m working from file:// URLs, where it’s not possible to set mime type). But then you can’t embed it on the page – you’d have to point to it from an embed tag or object tag.
  • You can inline the SVG if you write “pure” xhtml, and for this, you have to give the file a .xhtml suffix. As in this example.
  • I tried the Inject HTML into an iframe technique. I was hoping that with the right XML declaration and HTML type, I could convince the iframe it was hosting XHTML. But no, I could not. I’m still interested to know if there’s any way I could convince a dynamically generated iframe, with dynamic content, about the type of content it contains.

This is all part of some recent prototyping on an exciting TiddlyWiki project involving rich text editing, among other things. In a later blog post, I’ll explain how we’ve used this SVG stuff to mash up an online chart drawing tool with TiddlyWiki. I’m currently packaging it into a plugin.

4 thoughts on Inline SVG

  1. Same problem here, can’t get the svg filters, gradients and text paths work.Only the stroke and rotation effects work.I wonder what method does the cufon plugin use to render text….

  2. With svg injection into IFRAME the key moment is to set iframe’s src attribute to point to an existing svg document (served by http server with proper types). Once this existing image is loaded, iframe’s internals are correctly set to proper doctype. I haven’t tried to open()/write()/close() iframe’s document after that, but importNode() and consequent remove/appendChild() works like a charm cross-browser (FF,Opera10,WebKit).

Leave a Reply