Skip to content

Instantly share code, notes, and snippets.

@S1SYPHOS
Created February 17, 2018 23:54
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save S1SYPHOS/5d216e9d9c8cd6047e4b8847e4032f28 to your computer and use it in GitHub Desktop.
Save S1SYPHOS/5d216e9d9c8cd6047e4b8847e4032f28 to your computer and use it in GitHub Desktop.
SASS function to create an inline SVG url() source.
/*
* Replacing SVG strings in data-uri style situations
* by Jakob Erikson -- https://github.com/jakob-e
*
* http://codepen.io/jakob-e/pen/doMoML
*/
// Function to replace characters in a string
@function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
@if $index {
@return str-slice($string, 1, $index - 1) + $replace +
str-replace(str-slice($string, $index +
str-length($search)), $search, $replace);
}
@return $string;
}
// Function to create an optimized svg url
@function svg-url($svg){
// Chunk up string in order to avoid "SystemStackError: stack level too deep"
$encoded:'';
$slice: 2000;
$index: 0;
$loops: ceil(str-length($svg)/$slice);
@for $i from 1 through $loops {
$chunk: str-slice($svg, $index, $index + $slice - 1);
$chunk: str-replace($chunk,'"','\'');
$chunk: str-replace($chunk,'<','%3C');
$chunk: str-replace($chunk,'>','%3E');
$chunk: str-replace($chunk,'&','%26');
$chunk: str-replace($chunk,'#','%23');
$encoded: #{$encoded}#{$chunk};
$index: $index + $slice;
}
@return url("data:image/svg+xml;charset=utf8,#{$encoded}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment