svg-loader: A Different Way to Work With External SVG
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="/static/imghw/default1.png" data-src="/images/logo.svg" class="lazy" alt="svg-loader: A Different Way to Work With External 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="/static/imghw/default1.png" data-src="/icons/heart-blue.svg" class="lazy" alt="svg-loader: A Different Way to Work With External SVG" > <img src="/static/imghw/default1.png" data-src="/icons/heart-red.svg" class="lazy" alt="svg-loader: A Different Way to Work With External 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 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:
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 <script> tag, or in the JavaScript bundle). No extra code is needed.</script>
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:
But why?
This approach may feel unorthodox because it introduces a JavaScript dependency and there are already multiple ways to use SVGs, including inline and from external sources. But there’s a good case for using SVGs this way. Let’s examine them by answering the common questions.
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
-
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):
What about
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"></use> </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"></use> </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
The
<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
<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.
The above is the detailed content of svg-loader: A Different Way to Work With External SVG. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











I see Google Fonts rolled out a new design (Tweet). Compared to the last big redesign, this feels much more iterative. I can barely tell the difference

Have you ever needed a countdown timer on a project? For something like that, it might be natural to reach for a plugin, but it’s actually a lot more

Everything you ever wanted to know about data attributes in HTML, CSS, and JavaScript.

At the start of a new project, Sass compilation happens in the blink of an eye. This feels great, especially when it’s paired with Browsersync, which reloads

Tartan is a patterned cloth that’s typically associated with Scotland, particularly their fashionable kilts. On tartanify.com, we gathered over 5,000 tartan

The inline-template directive allows us to build rich Vue components as a progressive enhancement over existing WordPress markup.

PHP templating often gets a bad rap for facilitating subpar code — but that doesn't have to be the case. Let’s look at how PHP projects can enforce a basic

We are always looking to make the web more accessible. Color contrast is just math, so Sass can help cover edge cases that designers might have missed.
