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:


  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.

Ajax Programming Patterns – Podcast 3 of 4: “DOM Population” and “Code Generation and Reuse” Patterns

The third podcast in this series of Ajax Programming Patterns. The 29-minute podcast covers five patterns. As with the previous podcast, there is reason for concern about the audio quality herein. Firstly, three patterns on DOM population – taking server response data and displaying it or storing it in the DOM:

The second group of patterns (representing a different chapter in the Ajax Design Patterns book) are a couple of generic Javascript patterns to make the code more maintainable and portable: