Learn how to load a single SVG icon set from an external URL in order to take advantage of caching. This has the added benefit of not needing to include the same chunk of SVG on every page where icons are displayed. Since it’s the same resource being requested for each icon, the browser can cache the file as well.
Note: The SVG must be hosted on the same domain as the requested page.
Some older/less feature complete browsers don’t support this functionality. If you only care about the latest browsers, you can get away with not using a JavaScript polyfill (but you should still provide some sort of fallback). However, the svgxuse polyfill can help provide a cross browser experience, with the added necessity of a JavaScript dependency.
[00:00] We'll be working with the following sprite and SVG symbols. Notice that the outer SVG tag has an xml namespace attribute, and each symbol tag wraps the icon path, and each symbol has an ID and a view box. These are important for the icons to display properly.
[00:20] Let's start by adding an SVG tag, we'll give it a class of icon. Inside the SVG, I'll add a use tag, and I'll add an x-link:href attribute. I'll paste the URL to the sprite, and I'll append # and add the ID of plug. This is a fragment identifier, and it matches up with the corresponding ID on the symbol tag in the SVGs.
[00:50] To add other icons, we can just duplicate that code, and change plug to let's say star, and umbrella. You'll notice nothing is displaying and that's because the page that we're currently on is at a different domain than where the SVG is hosted, and that's a cores issue, and that's because cores is not supported for loading SVG symbols.
[01:15] If you're unable to load the SVG sprite from the same domain, maybe if you're loading it from a CDN, there's still hope. I'll include a polyfill called svgxuse, by adding a script tag, and in its source attribute I'll just link to that JavaScript file. Now when this code executes, the polyfill runs and our icons are visible.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!