Skip to content Skip to sidebar Skip to footer

Display Svg As Image From External Url

I have a Firebase storage bucket with svg files in it. The urls for each file are stored in Firestore. I am fetching the urls from firestore so I can display the svgs as images in

Solution 1:

With vanilla HTML5, if your want CSS isolation you need to place it in shadowDOM (supported in all modern browsers)

Either attach shadowDOM to your own <span> element;

Or take it one step further and create your own re-usable HTML Element <shadow-svg> (or any name you want)

Note: the SVG being an IMG src should be enough to not be affected by global CSS; so shadowDOM not strictly required. It ensures the IMG can not be styled by global CSS in this example.

<span id=SVG></span>

<shadow-svg src="https://svgshare.com/i/U7z.svg"></shadow-svg>
<shadow-svg src="https://svgshare.com/i/U7o.svg"></shadow-svg>
<shadow-svg src="https://svgshare.com/i/U7p.svg"></shadow-svg>

<style>
  #SVG {
    height: 130px;
    background: pink
  }
</style>

<script>
  SVG
    .attachShadow({
      mode: "open"
    })
    .innerHTML = `<style>:host{display:inline-block}img{height:130px;width:130px}</style>` +
    `<img src="https://svgshare.com/i/U7L.svg">`;

// OR

  customElements.define("shadow-svg", class extends HTMLElement {
    constructor() {
      super().attachShadow({
          mode: "open"
        })
        .innerHTML = `<style>:host{display:inline-block}img{height:130px;width:130px}</style>` +
        `<img src="${this.getAttribute("src")}">`;
    }
  });
</script>

Post a Comment for "Display Svg As Image From External Url"