I have a SVG image that I plan to reuse 50 – 150x times in my page, and as the page would be an infinite scroll, it could appear 1000x times or more
It is an upvote icon. I think of using the same icon, reversed, for a downvote
What is the most efficient way to include it ?
- Create a single file, link to it in an img tag, and use CSS to reverse it for downvotes ?
- Include the SVG code every single time ?
Will the HTML somehow optimize automatically the SVG code if seen many times in a page ? Or is it better to include SVG as code than as img tags ?
3
Answers
Ok so actually with the
<img>
tag it seems better as it is cached as drEr suggested in comments also inWhen multiple instances of same images are embedded in an HTML, does that load the image once?
Multiple image <img> tag with same source src
So I think I will go with the
<img>
tagWhy waste CPU time on elements that are not in the viewPort (yet)
You can use:
<img loading="lazy" src="[YOUR SVG]">
And yes, if it is the same
src
then the image is cached.<svg-vote> Web Component with IntersectionObserver API
Or, for more control like adding a EventListener and tracking how a user scrolled,
use a Web Component that only draws an SVG when it becomes visible in the viewPort using the IntersectionObserver API
https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver
Note: this does need JavaScript; for a non-JavaScript solution, see
ccprog
his answer.As long as the icon source code isn’t too complicated (containing filters, animations or interpolation tasks like color gradients), rendering performance should not be much of an issue, regardless of method used.
Loading times over the net also can be minimized with loading the icon code only once, or better yet, as part of another file loaded anyway. So adding the code once inside the HTML code, a script or a stylesheet for reuse might give you a tiny advantage over using an
<img>
tag.But note that the time at which the icon becomes available for rendering might differ depending on whether you use script or stylesheet, and what priority you set via
preload
and related attributes. Especially if you use a bulky JS framework, time to first render might be significantly delayed for a Component.The most elegant technique for embeding the icon in script is the Web Component, as shown in Danny Engelman’s answer.
Embedding in HTML code would need a hidden
<svg>
element somewhere on the page:a bit of CSS:
and some code to reference the template:
Embedding in a stylesheet would take advantage of a data url (note the URL escape of the
#
):For usage, that would only need