Storing them externally is a better option, but the only reliable way to use them is the <img> tag, which comes with severe limitations.
<!-- Can't modify the fill color if you want --> <img src="/path/to/img.svg" />
To solve this, I have created a library that offers all the benefits of inline SVGs, while still storing them externally. It's called svg-loader.
Check, for example, this logo of my project in SVG.
<img src="https://s2.svgbox.net/assets/logo-white.svg" />
Preview
Since the fill color is not defined, it will default to black and there's not much you can do about changing that. There are a few hacks around this using the filter property, but they are complex and not easy to modify.
In comes, svg-loader. You just have to drop the script in and the external SVGs will be fetched and injected inside the element. Like, this:
Preview
View on JS Fiddle
The library is very light <2KB (post-compression). The loads are lightning fast and also comes with a way to cache the file for longer. So, the image isn't fetched repeatedly. And pretty much works anywhere.
Compatible with React, Vue, Angular
svg-loader is framework agnostic and works with most front-end frameworks. You just need to include the library somewhere and everything else will be handled:
import React from 'react'import ReactDOM from 'react-dom'import 'external-svg-loader';class App extends React.Component {render () {return ( <svg data-src="https://s2.svgbox.net/materialui.svg?ic=mail" fill="currentColor" width="50px" height="50px" style={{ color: 'red' }} /> )}}ReactDOM.render( <App />, document.getElementById('container') );
View on Codesandbox
Note: The resources need to be compatible with the CORS policy since XHR is used to fetch them.
Src: Shubham Jain

No comments:
Post a Comment