Reputation: 146
I want to know the benefits of using Picture tag vs the CSS media query in-terms of pure performance (website load time). I am developing a website and clients are forcing me to use picture tag but I think both are same. Let me know your input.
<picture>
<source
media="(min-width: 650px)"
srcset="images/kitten-stretching.png">
<source
media="(min-width: 465px)"
srcset="images/kitten-sitting.png">
<img
src="images/kitten-curled.png"
alt="a cute kitten">
</picture>
or
using media query and targeting separate image tags.
Upvotes: 7
Views: 2188
Reputation: 61
I think the accepted answer/question is lacking some real world contextual details. When talking about performance, we're usually talking about performance on slower devices such as mobile devices, not desktops.
Example: If you are hiding a small image in desktop, in a desktop still small image will be downloaded but won't be shown (if it is hidden).
This is usually not a problem as desktops have faster processing and they don't run on data (larger bandwidth) unlike mobile devices.
The accepted answer never mentioned how CSS media queries behave on mobile devices - this method actually only applies the styles that satisfy the smallest media query. The reason why this method 'downloads' all styles on desktop is because of how media queries are usually written with mobile-first design, by setting a min-width criteria. So when loading the page in desktop, all your media queries would be satisfied thus they are all applied and the last one in the source order wins.
So in terms of performance on mobile devices, both methods are the same. Ultimately, the <picture>
tag is still the most robust solution due to additional configuration options with the srcset
attribute. However, sometimes you need to use CSS media queries instead of <picture>
tags such as when dealing with background images.
Here's a recent guide from Google recommending CSS media queries for optimizing background images: https://web.dev/optimize-css-background-images-with-media-queries/
Upvotes: 1
Reputation: 179
Media query works this way: Even when you are viewing a website in Desktop, it still downloads the styles of mobile.
Example: If you are hiding a small image in desktop, in a desktop still small image will be downloaded but won't be shown (if it is hidden).
Picture tag: If you have 3 different images for mobile, tablet and desktop. Picture tag will download only mobile device image when a page loads (when on mobile), it will neglect other 2.
If you want to test: 1. Write HTML code as you have above for 3 different images. 2. Once you are in desktop, load the page. Now you have a desktop image which you can see. 3. Disconnect the internet from your laptop. 4. In your browser responsive mode, keep reducing the screen 5. When it hits the tablet width, you will see the image won't be visible and it will be broken. 6. That means the image for tablet was not downloaded earlier when page load.
Upvotes: 9