Retrieving image size in the theme

The documentation gives examples on how to configure images in themes such that the browser would fetch the appropriate image size when loading, to help speed up page load times. Is there also a way to fetch the exact size of the image in the theme so that I can set the width and height of the image to prevent CLS?

I know other JS frameworks, such as Next.js, analyze the images at build-time and provides access to the image width and height early so that CLS can be avoided. It should in theory be possible for Ghost as well I believe where the server measures the image dimensions before rendering the handlebars.

P.S. Love open source projects like this.

Nice question. As far as I know, Ghost is already writing width/height attributes for images inside the post (for gallery or single images). For image elements on other places, I would expect that you can reach with width/height properties of the image reference. Like

width="{{ featured_image.width }}" height="{{ featured_image.height }}"

I attempted your idea, featured_image.width, however it does not seem to be implemented nor documented.

1 Like

I don’t have a quick setup to try, but I think image elements are actually objects that holds width/height properties. Maybe I’m wrong. @Cathy_Sarisky do you have any knowledge about this?

As far as I know, feature_image is only a url.

Hmm, I thought that Gallery card rendering is also part of Ghost template rendering and since gallery card html has width/height, I expected that image is an object. But just realized that post content html is rendered by Koenig, not Ghost itself. It’s writing width/height attributes while rendering those cards as HTML

So, yes. Apparently width/height of the images are not provided to templates for the image references. Even there is no data like that in the DB.