'Rmarkdown: include plot height in resulting html <img> tag

I am working on a larger RMarkdown-site. Due to the size of images on the pages I implemented lazy loading for images using the loading="lazy"attribute of the <img>tag by using the out.extra chunk option for knitr.

This worked nicely, but now I obviously have layout shifts e.g. when scrolling to the end of the document fast, since images are lazy-loading. The solution to this would be to specify the height and width attributes for the img tag

In my .html output, only the width is specified. Is there a way to make knitr also detect and include the height of the plot in the resulting <img>tag`?

PS: I know one can specify height and width in the chunk options, however I want to avoid doing this manually



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source