What is the correct way to utilize the `<svg>` element when loading external resources?

I have gone through numerous tutorials on how to add external SVGs to a webpage... such as this one:

The code I am using looks like this:

<svg>
  <use xlink:href="https://upload.wikimedia.org/wikipedia/commons/5/53/Skull_and_crossbones.svg"></use>
</svg>

However, the image is not loading, as demonstrated here: http://jsbin.com/cipacitovo/edit?html,output

Can anyone please point out what I might be doing wrong?

Answer №1

According to the SVG guidelines

In contrast to the 'image' element, the 'use' element is unable to reference entire files.

To specify which item within the image you want to display, you must include a fragment identifier in the URL.

If the file you are referring to lacks elements with id values, you must modify the file and assign ids to the elements you wish to reference.

Answer №2

With the demise of IE, all modern browsers now support Web Components.

You have the ability to craft your very own <load-svg> Web Component for fetching external SVG files, eliminating the necessity for symbol and use tags and seamlessly integrating them into your HTML document.

Utilizing shadowDOM is not mandatory, preventing any leakage of styles in or out and addressing the perennial issue of duplicate ID values in SVG files.

Minimal code required:

Tip: Embed this code within a <script> tag in the <head>

customElements.define("load-svg", class extends HTMLElement {
  // declare default connectedCallback as async so await can be used
  async connectedCallback(
    // call connectedCallback with parameter to *replace* an existing SVG 
    src = this.getAttribute("src"),
    // attach a shadowRoot if none exists (|| prevents displaying error when moving Nodes)
    shadowRoot = this.shadowRoot || this.attachShadow({mode:"open"})
  ) {
      // load SVG file from src="" async, parse to text, add to shadowRoot.innerHTML
    shadowRoot.innerHTML = await (await fetch(src)).text()

    // append optional <tag [shadowRoot]> Elements from inside <load-svg> after parsed <svg>
    shadowRoot.append(...this.querySelectorAll("[shadowRoot]"))

    // if "replaceWith" attribute 
    // then replace <load-svg> with loaded content <load-svg>
    // childNodes instead of children to include #textNodes also
    this.hasAttribute("replaceWith") && this.replaceWith(...shadowRoot.childNodes)
  }
})
path { fill: red }
load-svg,svg { display:inline-block; width:150px }
<load-svg src="https://svg-cdn.github.io/heart.svg"></load-svg>
<load-svg src="https://svg-cdn.github.io/heart.svg">
 <style shadowRoot>
   path { fill: green }
 </style>
</load-svg>
<load-svg replaceWith src="https://svg-cdn.github.io/heart.svg"> </load-svg>

There are two optional attributes available:

shadowRoot transfers the DOM element to shadowDOM

replaceWith substitutes the <load-svg> DOM element with the content of the loaded file (in this case, your <svg>)

Keep in mind: this Web Component is not limited to *.svg files; you have the capability to load any type of file.

Answer №4

Do not forget to include the

xmlns:xlink="http://www.w3.org/1999/xlink"
attribute within the <svg> tag.

Here is the correct way to do it:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <use xlink:href="https://upload.wikimedia.org/wikipedia/commons/5/53/Skull_and_crossbones.svg"></use>
</svg>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring AngularJS: A Guide to Accessing Millisecond Time

Is there a way to add milliseconds in Time using AngularJS and its "Interval" option with 2 digits? Below is the code snippet, can someone guide me on how to achieve this? AngularJs Code var app = angular.module('myApp', []); app.controller(&ap ...

Reverse the orientation of the SVG image, for instance, the graph

I've been experimenting with creating a bar graph using SVG, but I'm struggling to understand how it works. I tried rotating an existing graph upside down, but there seems to be a small offset. You can view the corresponding jsfiddle here - http: ...

Here is an example of how to transfer a value from PHP to a jQuery function in the code snippet provided

This is an example of my code. It is functioning properly even without passing a value. function displayMessage(text) { alert(text); } <button type="button" id="button" class="btn btn-success" onclick="displayMessage("Hello");"> Click Me </ ...

Mastering the Art of Live Search in Drop Down Multi Select

I need to develop a search functionality similar to the one found on . This search should allow users to select options from a dropdown menu or type their own search query, and provide live search results. I attempted to use the jQuery plugin https://www.j ...

One function is failing to execute properly due to multiple if conditions

Take a look at my JavaScript code below: function showLater1() { if ((vidos.currentTime >= 30) && (vidos.currentTime <= 34)) { lay.style.opacity = "1"; content.style.opacity = "0"; controls.style.opacity = "0"; ...

Mysterious issue with loading images in HTML and PHP

I've been dealing with a puzzling issue on my website design project. The logo image won't load in Firefox unless you hover over the ALT text, then it finally appears. However, this isn't an issue in IE where the logo displays properly. Thi ...

Repositioning a variable number of divs as the cursor hovers over the target area

Can anyone show me how to generate div elements in a loop using jQuery and change their position with the "mouseover" function? I've tried some code, but the positioning isn't changing correctly. Any suggestions on what needs fixing? var r, g, ...

A button featuring an extensive label that utilizes text-overflow ellipsis is initially set with a max-width of 700px. However, it should dynamically shrink when the viewport size decreases

My Request I need a button that can accommodate both long and short labels, with the text getting cut off at 700px using ellipses. The button should adjust to the available space when the viewport is smaller than 700px. The length of the label can vary gr ...

Use PHP code to echo a clear division after every third result in MySQL

I am currently displaying results in descending order from a MySQL table using a while loop. I have already set up a pagination system that displays 9 records per page. However, I am facing an issue when trying to implement a CSS break every 3 records in ...

Maximizing Efficiency: Utilizing a Single Panel across Multiple HTML Files with jQueryMobile

Can a panel defined in index.html be used on another page, such as results.html? Or do I have to define the panel on every page and duplicate the HTML code on each page? Because I want the panel to be consistent across all pages. This is the panel in my ...

Express Node + Styling with CSS

I am in need of a single EJS file (configuration includes Express and Request). app.get('/space', function(req, res){ res.render('space.ejs'); }); The file successfully renders, but only two out of three CSS stylesheet links work ...

Tips on Updating Array Value with jQuery

I have been working on using jQuery to edit array values. Here is my approach: From a modal, each time I click the "Add item" button, it pushes values to an array and appends the data to a table. var iteminfo = { "row": 'row' + cnt, "ma ...

When utilizing the JavaScript createElement() method to create elements on keydown, it will not be compatible with jQuery's draggable() method

I'm currently developing a drag and drop feature for a project, allowing users to add items to a work area and then position them by dragging. I'm facing an issue where I want to create multiple instances of the same element using a key code, but ...

Innovative: Enhancing column width dynamically without compromising grid integrity

Currently, I am utilizing Bourbon's Neat library to structure my grid system. Within my code, I have the following setup: section { @include outer-container; aside { @include span-columns(3); } article { @include span-columns(9); } } The chal ...

Struggling with evenly positioning 6 elements in two rows using CSS

For positioning 6 different elements on a webpage, I've experimented with various methods: I initially tried stacking two unordered lists vertically but faced issues with scaling when stretching the page. Another attempt was using a table, but I stru ...

Instructions on how to change the color of specific text to red

Issue: While working on my testimonials page, I am facing a problem with displaying an "ADMIN" tag in red color instead of normal stars for one of the responses by an admin. I have tried various solutions like removing the ending p tag and adding quotes to ...

Hiding Button in code behind

I have around 100 buttons in a list. Initially, I have set their visibility to false in the ASPX page. Now, I need to change the visibility to true from the code-behind when required. Since there are too many buttons, it's not feasible to individuall ...

A guide on defining the width of an element within a flex container when it overflows

Here is the code snippet I have: .divA { background: red; width: 500px; display: flex; flex-direction: row; overflow-y: scroll; } .epi { width: 50%; background: blue; } <div class="divA"> <div class="epi"> <h1>dsds ...

Is there a way to utilize the function body onload in jQuery?

I have some code that needs to be fixed. Currently, when I see <body onload="start()" onresize="resize()" onorientationchange="resize()">, I want the following code snippet to work: $("button").click(function(){ $("body").onload = start; or win ...

What is the best way to target CSS only to elements that do not have a parent with a specific class?

Striving to preserve the existing CSS in the codebase. .my-new-class { .existing-class { ...implementing new styles } } .existing-class { ...maintaining old styles } I attempted a technique that I know won't work and understand why: ...