When attempting to use the new loading="lazy"
attribute on an img
tag i get the following error:
[Intervention] An <img> element was lazyloaded with loading=lazy, but had no dimensions specified. Specifying dimensions improves performance. See https://crbug.com/954323
When looking online, i came across the follow link specifies that adding width
and height
attributes to the img
helps the browser avoid reflow by painting a placeholder to the screen:
https://web.dev/native-lazy-loading#image-loading
My question is, it's pretty uncommon these days to hard code a width
and height
of an image, if i override these in my style sheet with something like the following, will i still benefit from avoiding reflow?
img {
width: 100%;
height: auto;
}
Thanks in advance Sami.
Short answer is no... Even if 'reflow' behaviour is strictly dependent on the browser's implementation, it's pretty valid to assume that almost any modification of the DOM will lead to a 'reflow', especially if it involves changing dimensions (elements displacing other elements) or adding/removing a node. It would be still advisable to add height and width attributes that will not only suppress the error/warning, but will also work as a fallback.
Most importantly, you will avoid an ugly 'jump' effect when the image loads if the written height/width matches the final style.
Additional note: 'reflows' are to be avoided when possible, but in your case, image loading will happen only once, so I would say It doesn't matter.
As Ernesto Stifano mentions, there is no way to get around the reflow issue without specifying the ratio of the image (i.e. letting the browser know a width and height attribute for the image).
If you don't want to specify an exact width and height though, you can add an intrinsicsize
attribute instead (see here) but you still need to set a width and height property (using the interface intrinsicsize="300 x 400"
, for example).
This can allow you to be able to set width: 100%
in the CSS and not have to worry about setting height: auto
constantly, which may help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With