Skip to content

Instantly share code, notes, and snippets.

@0kenx
Forked from jennyknuth/README.md
Created January 15, 2024 02:02
Show Gist options
  • Select an option

  • Save 0kenx/64da99eb3c8c29ac81775ac0092c8d35 to your computer and use it in GitHub Desktop.

Select an option

Save 0kenx/64da99eb3c8c29ac81775ac0092c8d35 to your computer and use it in GitHub Desktop.
Transform an SVG into a data URI—best practice

Using a data URI is a nice way to include a web resource without needing to make an HTTP request. Chris Coyier explains the technique nicely in Probably Don't Base64 SVG.

While a PNG might use Base64 encoding, for SVG, there is a better way.

Taylor Hunt's experiments led to this solution for optimizing SVGs in data URIs:

"So the best way of encoding SVG in a data URI is data:image/svg+xml,[actual data]. We don’t need the ;charset=utf-8 parameter (or the invalid ;utf8 parameter…), because URLs are always ASCII."

Here is a step-by-step method to create your encoded SVG string to include as a data URI:

  • 1 run your SVG file through svgo.

  • 2 In your text editor, replace all double quotes in your SVG file with single quotes. Make sure there are no line breaks.

  • 2 Replace all non-ASCII and URL-unsafe characters by running your svg string through an encoding function like the one below—surround your svgString with double quotes in the function's argument.

  • 1 Paste your encoded SVG into your html tag's src attribute or css's url call using double quotes, after the data:image/sg+xml, prefix.

Examples:

HTML:

<img src="data:image/svg+xml,%3Csvg width='247' height='34' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23FFF' fill-rule='non.zero'%3E%3Cpath d='M13.918 ... 4.022-2.888 4.57V26h-4.46V7.975z' fill='%23D7DCE1'/%3E%3C/g%3E%3C/svg%3E"/>

CSS:

.bg {
  background: url("data:image/svg+xml,%3Csvg ... /svg%3E");
}

Let me know if any questions.

// this function is from the work of Taylor Hunt found at https://codepen.io/tigt/post/optimizing-svgs-in-data-uris
function encodeSvg(svgString) {
return svgString.replace('<svg',(~svgString.indexOf('xmlns')?'<svg':'<svg xmlns="http://www.w3.org/2000/svg"'))
//
// Encode (may need a few extra replacements)
//
.replace(/"/g, '\'')
.replace(/%/g, '%25')
.replace(/#/g, '%23')
.replace(/{/g, '%7B')
.replace(/}/g, '%7D')
.replace(/</g, '%3C')
.replace(/>/g, '%3E')
.replace(/\s+/g,' ')
//
// The maybe list (add on documented fail)
//
// .replace(/&/g, '%26')
// .replace('|', '%7C')
// .replace('[', '%5B')
// .replace(']', '%5D')
// .replace('^', '%5E')
// .replace('`', '%60')
// .replace(';', '%3B')
// .replace('?', '%3F')
// .replace(':', '%3A')
// .replace('@', '%40')
// .replace('=', '%3D')
;}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment