Last active
May 15, 2017 18:22
-
-
Save mvsde/046ab3390cb1f43c43f98f31ba1df759 to your computer and use it in GitHub Desktop.
Cross-browser inline SVG function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SVG URL | |
// | |
// Generate an escaped SVG for data URIs. | |
// | |
// Usage: | |
// .selector { | |
// background-image: svg-url('<svg>…</svg>'); | |
// } | |
// | |
// Source: | |
// http://codepen.io/jakob-e/pen/doMoML | |
// ============================================================================= | |
@function svg-url($svg){ | |
// Chunk up string in order to avoid | |
// "stack level too deep" error | |
$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); | |
// Encode (may need a few extra replacements) | |
$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}"); | |
} | |
// STR-REPLACE | |
// | |
// Helper 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment