How to reserve space for a variable size image before the image load so that layout shift can be avoided?

Viewed 23

I have an html page which contains text, an image tag, and again some text as follows:

This is text before the image.

    <img src="image.jpeg"/>


This is text after the image.

Now when the page loads, the texts loads before the image since image takes longer to load. Because of this there is a layout shift, i.e., The text after the image appears just after the text before the image without any space for the image if the image has not loaded yet. However, when the image loads, the text after the image moves below, i.e., layout shift occurs. How to reserve space for the image before image load so that layout shift does not occur? Also, there can be any image in the image tag and image size is also dynamic. The image with the original size has to be displayed on the page. Furthermore, since I am using server side rendering, I know the size of the image to be displayed before hand. I cannot fix the height and width of image because that will cause issue in the responsiveness of image when the display size changes, the image will not longer adapt to the size of the screen.

1 Answers

1- put your image in a container.

2- give the container a fixed width and height, and a fixed min-height and min-width as you wish or as the picture resolution.

that's it.

don't worry about the js code, I just put it to show the image after 3 seconds to help you understand what I mean.

var image = document.querySelector(".image");
image.style.display = "none";
setTimeout(() => {
    image.style.display = "block";
}, 3000);
.image-container {
  width: 350px;
  min-width: 350px;
  height: 250px;
  min-height: 250px;
  border: 1px solid red;
}

.image { 
  width: 350px;
  min-width: 350px;
  height: 250px;
  min-height: 250px;
}
 <h2 class="before">This is text before</h2>
 <div class="image-container">
  <img class="image" src="https://images2.minutemediacdn.com/image/fetch/w_850,h_560,c_fill,g_auto,f_auto/https%3A%2F%2Fwinteriscoming.net%2Ffiles%2F2021%2F11%2FCaraxes-850x560.jpeg" alt="">
 </div>
 <h2 class="after">This is text after</h2>

Related