Minifying SVG and Embedding It Into HTML (a.k.a. Base64-encoding SVG)

Case: Assets such as PNG logos sometimes load shortly after the content, rendering their alt content visible for a moment, distorting page design.

Solutions

A vector substitute is much more appropriate as it scales flawlessly on different resolutions, has a small size and displays instantly, once embedded into the page code.

If no vector version is available, the PNG can be traced with InkScape or similar software and then exported to “plain SVG”.

Once the SVG file is present:

Solution A

  1. Optimize it by uploading/pasting to SVGOMG
  2. Minify it with mini-svg-data-uri at RunKit

mini-svg-data-uri Usage:

var svg = '<svg .. ></svg>'; // optimized svg content goes here

var svgToMiniDataURI = require('mini-svg-data-uri');

var optimizedSVGDataURI = svgToMiniDataURI(svg);

Notes on Usage:

  • The resulting Data URI should be wrapped with double quotes: url(“…”), <img src=”…”>, etc.
  • This might change or break SVGs that use ” in character data, like inside <text> or aria-label or something. Try curly quotes (“”) or &quot; instead.

Solution B (backup)

In case the end result is of Solution A is broken:

  1. Optimize it by uploading/pasting to SVGOMG
  2. Open the resulting file in a text editor
  3. Search: "
    and replace: '
  4. Search: <
    and replace: %3C
  5. Search: >
    and replace: %3E
  6. Search: #
    and replace: %23
  7. Search: /
    and replace: %2F
  8. Prepend code with: data:image/svg+xml,

Refer to the reference at the HTML URL Encoding Reference in case not all characters are escaped. You know that’s the case when the image is not rendering.

Example end result:

<img src="data:image/svg+xml,%3Csvg xmlns='https:%2F%2Fwww.w3.org%2F2000%2Fsvg' width='960' ..." alt='Company.com'>

Sources

Misc

Was this post helpful?