Troubleshooting Cross-Browser Compatibility with srcset Attribute in HTML img Tag

I'm using the srcset attribute of the IMG tag to display three different images on three different viewports. However, I've run into an issue where this srcset attribute isn't working correctly in Chrome and Safari browsers, although it works fine in Firefox. Can anyone help me in providing the best solution for ensuring compatibility across all browsers? Here's the link to my codepen: https://codepen.io/Amit-Soni-the-vuer/pen/bGJoGxM
Amit Soni
CodePen
img
...
2 Replies
Kevin Powell
Kevin Powell3mo ago
I think you want to use the picture element, and not a regular img . picture is for art direction, where you can load in different images. when you use srcset, the purpose is to load in the best image for the screen size, so that you don't download something too heavy for no reason (you can also use it to make sure you're getting a higher quality image for high-resolution devices). Chrome and Safari are both doing this fine. Make the preview side of the codepen small, and make a change to the HTML so that it refreshes the viewport, and it'll use the appropriate image for the size. Then, if you make the viewport bigger, it means it's allowed to now load in the other source, and use that instead. Because it's an <img>, it's assuming all the sources are the same, but different resolutions, so once it's loaded in a higher-res one, it keeps using that image, it won't switch it back out at smaller sizes again.
amitsoni
amitsoni3mo ago
Thank you, Kevin, for the explanation. It worked perfectly. Here is the link to the CodePen - https://codepen.io/Amit-Soni-the-vuer/pen/bGJoGxM
Amit Soni
CodePen
img
...