Samuel
Samuel

Reputation: 2635

Native lazy load image reflow (loading='"lazy")

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.

Upvotes: 5

Views: 6117

Answers (3)

Ernesto Stifano
Ernesto Stifano

Reputation: 3130

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.

Upvotes: 5

mfranzke
mfranzke

Reputation: 131

additionally to what Ernesto Stifano has mentioned previously, the current development regarding "intrinsicsize" is more or less to "Compute img/video/canvas aspect ratio from width and height HTML attributes" - compare to https://github.com/web-platform-tests/wpt/pull/18945 and https://github.com/WICG/intrinsicsize-attribute/issues/16

Upvotes: 0

Oliver
Oliver

Reputation: 3138

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.

Upvotes: 2

Related Questions