In the video embedded below, Jen Simmons explains how to improve image loading by using width and height attributes. The issue is that there’s a lot of jank when an image is first loaded because an
img will naturally have a height of
0 before the image asset has been successfully downloaded by the browser. Then it needs to repaint the page after that which pushes all the content around. I’ve definitely seen this problem a lot on big news websites.
Anyway, Jen is recommending that we should add
width attributes to images like so:
<img src="dog.png" height="400" width="1000" alt="A cool dog" />
This is because Firefox & Chrome will now take those values into consideration and remove all the jank before the image has loaded, even when you override those values in CSS with a fluid width and thus unknown height. That means content will always stay in the same position, even if the image hasn’t loaded yet. In the past, I’ve worked on a bunch of projects where I’ve placed images lower down the page simply because I want to prevent this sort of jank. I reckon this fixes that problem quite nicely.
I thought that was a standard for years
It kinda was, particularly in fix-width designs, where the width/height attributes were actually the size the image rendered at. Then that went out the door when we all started doing flexible media. These days it’s rare to see an image that isn’t
max-width: 100%. And as soon as an image has a flexible width, that means the height is unknown until it downloads because the height is based on the aspect ratio of the image.
So this change is kinda like wink wink nudge nudge – we know this isn’t the size the image will end up rendering, it’s just a way for you to tell us about its aspect ratio, and we’ll reserve space in this fluid design based on that. It’s cool.
Is this effectively an aspect ratio? For example, if we replace the numbers in the article with 4 and 10 respectively (or 2 and 5), we would achieve the same benefit?
Neat. All of our images use the padding percentage as aspect ratio trick, so not sure this has much utility until the aspect ratio property has full browser support. Until then, wrapping divs for all images!
do we have any caniuse page to check the state of this feature in different browsers?…
will this applicable to normal non-replaced
<div>elements if not , we left with padding hack to give the proper aspect ratio without jank, or we can use the aspect-ratio css property
, this technique will work without jank?, what is the calculated width of the image now