I’ve been puzzling over a performance issue on one of my sites lately and finally got it figured out today.
A custom shortcode uses the_post_thumbnail()
to include a small image (~250px square); I have a bunch of custom image sizes set up, so the srcset
attribute included 16 different image sizes. (Overkill? Maybe….) However, instead of using the image closest to 250px wide, Chrome was pulling in the largest available image—sometimes as much as 1500px! Obviously, this is terrible for performance.
In addition, certain pages had dozens of these images, multiplying the effect. My test-case page was 10+MB total (way too heavy…).
Here’s a sample <img>
tag for one of my images:
I finally realized that the root cause was that the sizes
attribute was set to “100vw,” basically suggesting to the browser that the image might at some point be rendered at 100% width of the viewport, so my browser was happily pulling down the largest possible image so it could display it in all of its high-resolution, hundred-KB glory instead of the scaled dozen-KB file.
Since I know this particular shortcode will only show images at a max width of 250px, I needed to set the sizes
attribute to “250px,” hinting to the browser that anything slightly larger than that would be perfectly adequate.
Here’s how I handled it:
- Added a filter to
wp_get_attachment_image_attributes
and checked for a named image size or array - If it was an array, I set the
sizes
attribute to that pixel size - If it was a named image size, I set the
sizes
attribute to that pixel size
Sample code:
This approach admittedly is a bit heavy-handed and I’m still testing out the behavior on other pages on the site, but this fixed the problem with that specific shortcode, and my test page went from 10+MB to ~5MB—it cut my page weight in half!
The moral of the story is don’t “set it and forget it,” especially when adding responsive images using custom code.
Thanks to VIA Studio for their blog post that finally made the solution click for me.