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:
<img src="/images/logo.svg" />
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.
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?
<img src="/icons/heart-blue.svg" /> <img src="/icons/heart-red.svg" />
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
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:
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
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
Dynamically-added elements and change in attributes are also handled automatically, which ensures that it works with all web frameworks. Here’s an example in React:
Can we not just inline SVG ourselves?
Inlining is the simplest way to use SVGs. Just copy and paste the SVG code in the HTML. That’s what svg-loader is ultimately doing. So, why add the extra steps to load a SVG file from somewhere else? There are two major reasons:
- Inline SVGs make the code verbose: SVGs can be anywhere from a few lines to a few hundred. Inline SVGs can work well if what you need is just a couple of icons and they are all tiny. But it becomes a major pain if they are sizeable or many, because then, they become long strings of text in code that isn’t “business logic.” The code becomes hard to parse.
It’s the same thing as preferring an external stylesheet over a
<style>tag or using images instead of data URIs. It’s no wonder that in React codebases, the preferred approach is to use SVG as a separate component, rather than define it as a part of JSX.
- External SVGs are much more convenient: Copying and pasting often does the job, but external SVGs can be really convenient. Say you’re experimenting with which icon to use in your app. If you’re using inline SVGs, that means going back and forth to get the SVG code. But with external SVGs, you only have to know the name of the file.
Take a look at this example. One of the most extensive icon repository on GitHub is Material Design Icons. With svg-loader and unpkg, we can start using any of 5,000+ icons right away.
Isn’t it inefficient to trigger an HTTP request for every SVG versus making a sprite?
Not really. With HTTP2, the cost of making an HTTP request has become less relevant. Yes, there are still benefits of bundling (e.g., better compression), but for non-blocking resources and XHRs, the pros are almost non-existent in real-world scenarios.
Here’s a Pen loading 50 icons in a similar fashion as above. (Open in incognito mode as the files are cached by default):
<use> tag (SVG symbols)?
SVG symbols separate the definition of the SVG file from its use. Instead of defining the SVG everywhere, we can have something like this:
<svg> <use xlink:href="#heart-icon" /> </svg>
The problem is that none of the browsers support using symbols files hosted on a third-party domain. Therefore, we can’t do something like this:
<svg> <use xlink:href="https://icons.com/symbols.svg#heart-icon" /> </svg>
Safari doesn’t even support symbols files hosted on the same domain.
Can we not use a build tool that inlines the SVGs?
I couldn’t find an obvious way to fetch SVGs from a URL and inline them in common bundlers, like webpack and Grunt, although they exist for inlining SVG files stored locally. Even if a plugin that does this exists, setting up bundlers isn’t exactly straightforward. In fact, I often avoid using them until the project has reached acertain level of complexity. We must also realize that a majority of the internet is alien to things like webpack and React. Simple scripts can have a much wider appeal.
What about the
<object> tag is a native way to include external SVG files that work across all the browsers.:
<object data="https://unpkg.com/[email protected]/svg/access-point-network.svg" width="32" height="32"></object>
However, the drawback is we’re unable to customize the SVG’s attributes unless it’s hosted on the same domain (and the
fill, like this:
<object data="https://unpkg.com/[email protected]/svg/access-point-network.svg" width="32" height="32" onload="this.contentDocument.querySelector('svg').fill = 'red'"></object>
In short, using external SVG files this way makes it ultra-convenient to use icons and other SVG assets. As covered earlier, with unpkg, we can use any icon on GitHub without needing extra code. We can avoid creating a pipeline in a bundler to process SVG files or a component for every icon, and just host the icons on a CDN.
Loading SVG files this way packs a lot of benefits with very little cost.
Great idea! I did something really similar to load icon sets using a custom element recently
Did you consider using a custom element (svg-loader ?) instead of regular tags ?
While I think your approach is great for regular svgs, it might be a little verbose for iconsets… I’m wondering now if there might be a way to combine the best of both worlds to allow aliasing iconsets while allowing loading “regular” svg illustrations/logos.
Nice work! I published an an SVG manager last year but instead of caching I decided to harness a reference sheet approach. One of the tricky things is setting up external svgs, so the package helps you do that by processing the assets too with a CLI script.
Well done! I just tried this out, and it seems to work very well.
I also really appreciate the time you took to overcome many of the performance issues I was thinking about when I first started reading this article.
I believe that custom variables are inherited, eg.:
Alternativelay, optional parts of the source file can be excluded/included with eg.
<use href="#part-optional-1" style="--fill: orange" />.
hello, really nice work there. quick question: does it support locally stored svgs?
Yes, if you’ve a SVG that’s accessible like this: /path/to/icon.svg. You can use it via:
This seems to be awesome.
but I’m trying to run it with parcel on a html page and it returns blank svg
there is no mentioning of safari on the linked resource https://css-tricks.com/svg-use-external-source/…
I deleted the svg source but it still loading svg. I changed the source but it still loading previous svg from nowhere(maybe cache). how to solve this?