Hi there,
I would like to understand how other developers approach image optimization in HubSpot. In particular, I would like to figure out how to set the width and height attributes on all images because:
a. this is best practice and helps reduce layout shift; and
b. this would allow me to make use of HubSpot’s srcset feature (if you set the width attribute on an image, HubSpot automatically generates a srcset attribute for you)
However, for most of our modules, the content editor has the flexibility to upload an image of any size, so I have no way to predict the width and height, or even the aspect ratio. We just use percentage-based values in css to set the size of the image relative to its container. From a styling perspective, this works fine, but it makes it hard to optimize for performance.
Even if I could get the width and height dynamically (e.g., maybe from the module image field where the content editor can set an exact width and height), I would almost always want to use scaled-down sizes for the width and height attributes. HubSpot generates the srcset sizes at 0.5x, 1x, 1.5x, 2x, 2.5x, and 3x, relative to the width attribute value. The images that are uploaded are usually quite large, so I want srcset to generate smaller images, not larger ones. That means I need to set the width attribute to be smaller than the inherent width. I thought about just taking the inherent width and scaling it down by a fixed amount with a calculation. However, the width and height attributes only accept integer values, and since I can’t predict the aspect ratio, I don’t think I can write a calculation that would guarantee integers while preserving aspect ratio.
I’m stumped. Am I thinking about this all wrong? How do other developers handle this? Do you have strict requirements on the image dimensions your content editors can upload? Do you just forego the width and height attributes?
Thanks,
Ashleigh