tigt / mini-svg-data-uri

Small, efficient encoding of SVG data URIs for CSS, HTML, etc.
https://npm.runkit.com/mini-svg-data-uri
MIT License
309 stars 16 forks source link

Compact version #24

Open killroy42 opened 1 year ago

killroy42 commented 1 year ago

Just wanted to leave this here in case somebody is looking for something more compact. Turned out my use case didn't include any colors matching those in here, and as that added a lot of code size, I compacted it down to the code below, which seems to work well for my use case in sudokupad.app. This could probably minified quite a lot as it's still fairly verbosely-formatted and named.

const svgToTinyDataUri = (() => {
    // Source: https://github.com/tigt/mini-svg-data-uri
    const reWhitespace = /\s+/g,
        reUrlHexPairs = /%[\dA-F]{2}/g,
        hexDecode = {'%20': ' ', '%3D': '=', '%3A': ':', '%2F': '/'},
        specialHexDecode = match => hexDecode[match] || match.toLowerCase(),
        svgToTinyDataUri = svg => {
            svg = String(svg);
            if(svg.charCodeAt(0) === 0xfeff) svg = svg.slice(1);
            svg = svg
                .trim()
                .replace(reWhitespace, ' ')
                .replaceAll('"', '\'');
            svg = encodeURIComponent(svg);
            svg = svg.replace(reUrlHexPairs, specialHexDecode);
            return 'data:image/svg+xml,' + svg;
        };
    svgToTinyDataUri.toSrcset = svg => svgToTinyDataUri(svg).replace(/ /g, '%20');
    return svgToTinyDataUri;
})();
tigt commented 1 year ago

I don’t have strong feelings about this one way or another, but I realized I should probably respond at some point so it doesn’t seem like I’m being rude.

Even beyond this, once evergreen browsers snuff out the last remainders of IE and the other engines that occupied the weird middle ground of “tolerates some unescaped URL characters”, mini-svg-data-uri will probably be unnecessary to the point you could merely replace " and # with vanilla JS.

killroy42 commented 1 year ago

Since I recently implemented code that records 100s of frames of SVG images to generate a GIF animation from, I double checked what I was using to urlify the SVG data, and it seems to be exactly what you suggested:

frames.push(`data:image/svg+xml;utf8,${encodeURIComponent(svg)}`);
Danny-Engelman commented 4 months ago

Modern Browsers do not require escaped < and > in DataURIs

killroy42 commented 4 months ago

Modern Browsers do not require escaped < and > in DataURIs

It's for all the other characters that need to be escaped. A custom encoder can make the result more compact, but is of course more complex code. I use a custom encoder in production.

Danny-Engelman commented 4 months ago

It's for all the other characters that need to be escaped.

Since I didn't have to support IE anymore (lucky me 8 years now), I have only encoded the # , but maybe there are (URL) characters I haven't used in my SVGs