SVGs are awesome: they are small, look sharp on any scale, and can be customized without creating a separate file. However, there is something I feel is missing in web standards today: a way to include them as an external file that also retains the format’s customization powers.
For instance, let’s say you want to use your website’s logo stored as web-logo.svg. You can do:
That’s fine if your logo is going to look the same everywhere. But in many cases, you have 2-3 variations of the same logo. Slack, for example, has two versions.
Even the colors in the main logo are slightly different.If we had a way to customize fill color of our logo above, we could pass any arbitrary color to render all the variations.
Take the case of icons, too. You wouldn’t want to do something like this, would you?
Load external SVGs as inline elements
To address this, I have created a library called svg-loader. Simply put, it fetches the SVG files via XHR and loads them as inline elements, allowing you to customize the properties like fill and stroke, just like inline SVGs.
For example, I have a logo on my side-project, SVGBox. Instead of creating a different file for every variation, I can have one file and customize the fill color:
CodePen Embed Fallback
I used data-src to set the URL of SVG file. The fill attribute overrides fill of the original SVG file.
To use the library, the only thing I have to ensure is that files being served have appropriate CORS headers for XHRs to succeed. The library also caches the files locally, making the subsequent much faster. Even for the first load, the performance is comparable to using tags.
This concept isn’t new. svg-inject does something similar. However, svg-loader is easier to use as we only have to include the library somewhere in your code (either via a