skip to Main Content

I have some SVG in a list, there are about 100 nodes. They looks like:

<li>
  <div class="icon"><svg><path .... </svg></li></div>
</li>
... another 1000 <li>

Should I turn them into CSS?

<li>
  <div class="icon"></li></div>
</li>

.icon {
  width:20px;
  height:20px;
  background-image: url( "data:image/svg+xml,%3Csvg
}

Will the second way save some resource as the SVGs are not in the DOM tree?

2

Answers


  1. Yes, to put the svgs in your css can improve your performance.

    I can think of three reasons:

    1. DOM Complexity is being reduced:
      The amount of nodes in your HTML document is being reduced. Usually a smaller DOM tree leads to faster rendering.

    2. Caching: CSS files are cached by the browser, which will improve subsequent page loads.

    3. HTTP Request Reduction: When you serve the svg as files there will be a lot HTTP requests. To serve them directly in css or html will reduce those extra requests and improve your page load time.

    Keep in mind that if you use a lot of very complex svgs your css file size will increase and the complexity of your file can be increased as well. But if you won’t change them too often, this shouldn’t be a problem.

    However if you want to manipulate or style the svgs it could be better to use them as inline SVGs in your HTML.

    Login or Signup to reply.
  2. For performance see: https://cloudfour.com/thinks/svg-icon-stress-test/

    Personally I would wrap it in a Web Component, most flexible during authoring time, makes it easy to change it anytime I want

    quick and dirty:

    <script>
    customElements.define("li-svg", class extends HTMLElement {
      connectedCallback(){
        setTimeout( ()=> this.innerHTML = `<li><div class="icon">${this.innerHTML}</li></div>`);
      }
    });
    </script>
    
    <ul>
      <li-svg>Foo</li-svg>
      <li-svg>Bar</li-svg>
      <li-svg>Boo</li-svg>
    </ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search