user3429445
user3429445

Reputation: 101

SVG use multiple, load once

I want to use the same SVG twice on my page, but only load it once.

I'm manipulating the CSS of the SVG with JS, so I think the SVG needs to be in directly in the HTML as opposed to using an object.

The manipulation is the same for both SVG's, they should be exact replica's, so I really don't want to have to load it twice.

Any way for me to do this?

Thanks, James

Upvotes: 4

Views: 4250

Answers (1)

Bob  Sponge
Bob Sponge

Reputation: 4738

svg {
   color: green;
   width: 20px;
   height: 20px;
}
<!-- define SVGs -->
<div style="visibility: hidden; position: absolute; width: 0px; height: 0px;">
  <svg xmlns="http://www.w3.org/2000/svg">
  <symbol viewBox="0 0 18 15" id="sample">
    <path d="M17.9 1.85L7.675 12.318 6 14.03l-1.676-1.713L.1 8.002c-.15-.162-.146-.43.01-.597l1.07-1.15c.155-.168.403-.172.554-.01L6 10.605 16.266.094c.15-.163.4-.16.555.008l1.07 1.152c.156.167.16.435.01.596z" fill="currentColor" fill-rule="evenodd"></path>
    </symbol>
  </svg>
</div>

<!-- and use it whenever you want -->
<svg><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sample"></use></svg>

<svg><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#sample"></use></svg>

Upvotes: 8

Related Questions