Converting SVG text string to blob for image source

It is simple to compose an SVG image as a string of text, convert the string to a blob, and use the blob as an image element source…with one “gotcha”.

The implementation:

const svg = `...`;
const blob = new Blob([svg], {type: 'image/svg+xml'});
const url = URL.createObjectURL(blob);
const image = document.createElement('img');
image.addEventListener('load', () => URL.revokeObjectURL(url), {once: true});
image.src = url;

However, the following does not work:

const svg = `
<svg width="50" height="50">
<circle cx="25" cy="25" r="20"/>

This produces a broken image:

No xmlns on <svg>

The xmlns attribute must be included on the <svg>element:

const svg = `
<svg xmlns="" width="50" height="50">
<circle cx="25" cy="25" r="20"/>

And it works:

Yes xmlns on <svg>

Chrome is not tolerant of a missing xmlns attribute in this case, which is, I guess, consistent: only inline <svg>s, embedded inside HTML markup, are allowed to omit the xmlnsattribute on the <svg> tag. It seems that external SVGs (used as the src of an <img>) must include it, even if the content of the SVG is “inline” in the sense that it is blob, and even if the MIME type is image/svg+xml.