Why You Should Always Give Lazily Loaded Images A Width & Height

When images are set to load lazily they will only be downloaded when they come into view but what counts as "in view"? It seems Google Chrome only takes the vertical scroll position into account but Firefox will check if the image is intersecting the viewport. This can causes some funkyness if your images don't have a height or width defined.

Image Loading Background

When the browser is rendering a page and comes across an image it will make a request to download but won't wait for it, it will just carry on. If the image has its width or height defined, then the browser will leave a gap where the image will be once it downloads. But if not, the image becomes size-less, a 0 x 0px element.

The Problem

When Firefox checks if an image that is marked for lazy loading should be downloaded, it looks to see if it intersects the viewport. Seems reasonable: is the image on the users screen? If yes, download it. But this causes issues for images that overflow the viewport. For example if a site has a 100 x 100px lazily loaded image which slightly overflows the side of the page and hasn't been given dimensions, then Firefox will never download it.

Why not?

The key is that before the image is downloaded it is treated as a 0x0px image. This means that if the image overflows by even 1px it will be entirely out of view even if, had it been downloaded, it would've been visible. Chicken meet egg, egg meet chicken etc etc.

Conclusion

Explicitly define lazily loaded image dimensions - either via the width and height attributes or through CSS properties - or Firefox might not display them. This is good practice anyway as it reduces layout jumps caused by the browser relaying out the page when a image suddenly takes up some space.

Popular Reads

Subscribe

Keep up to date

Please provide your email address
Please provide your name
Please provide your name
No thanks