Setting image width and height attributes when image size is unknown

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

Hi, @ahalverstadt :waving_hand: Welcome to our community! Thanks for your question.

I’d like to invite some of our community members to the conversation — hey @Jnix284 @Anton @Stephanie-OG, do you have any best practices or tips you can share with @ahalverstadt?

Thank you for taking a look! — Jaycee

@ahalverstadt the short answer is that you use srcset to control the responsiveness and within the module where they can upload the image, you have width and height properties that can be adjusted and populate the width and height with pixels rather than percentage.

The long answer would require a lot of code - if you’re new to developing in HubSpot and if you haven’t already, I suggest joining the HubSpot Developer Slack where you can ask more specific code questions and meet others who you can learn from.

When I was getting started, I downloaded several free themes and explored the different ways images where handled.