Should I use ,
, or
for loading SVG files into a page in a way similar to loading a
jpg
srcset
Most current browsers today support the srcset attribute, which allows specifying different images to different users. For example, you can use it for 1x and 2x pixel density, and the browser will select the correct file.
In this case, if you specify an SVG in the srcset
and the browser doesn't support it, it'll fallback on the src
.
<img src="logo.png" srcset="logo.svg" alt="My logo">
This method has several benefits over other solutions:
srcset
should know how to handle it so that it only downloads the file it needs.The best option is to use SVG Images on different devices :)
<img src="your-svg-image.svg" alt="Your Logo Alt" onerror="this.src='your-alternative-image.png'">
My two cents: as of 2019, 93% of browsers in use (and 100% of the last two version of every one of them) can handle SVG in <img>
elements:
Source: Can I Use
So we could say that there's no reason to use <object>
anymore.
However it's still has its pros:
When inspecting (e.g. with Chrome Dev Tools) you are presented with the whole SVG markup in case you wanted to tamper a bit with it and see live changes.
It provides a very robust fallback implementation in case your browser does not support SVGs (wait, but every one of them does!) which also works if the SVG isn't found. This was a key feature of XHTML2 spec, which is like betamax or HD-DVD
But there are also cons:
<object>
(tho it's perfectly safe to use it with <amp-img>
and use it inline too.<object>
tag might keep your PWA from being really offline capable.