54

I have a few images on my page. I'm finding that the page starts to render before the images have been loading (which is good), but that the visual effect is not great. Initially the user sees this:

 --------hr--------
 text

Then a few milliseconds later the page jumps to show this:

--------hr--------
[           ]
[   image   ]
[           ]
text

Is there a simple way that I can show a grey background image of exactly the width and height that the image will occupy, until the image itself loads?

The complicating factor is that I don't know the height and width of the images in advance: they are responsive, and just set to width: 100% of the containing div. This is the HTML/CSS:

<div class="thumbnail">
<img src="myimage.jpeg" />
<div class="caption">caption</div>
</div>
img { width: 100% } 

Here's a JSFiddle to illustrate the basic problem: http://jsfiddle.net/X8rTB/3/

I've looked into things like LazyLoad, but I can't help feeling there must be a simpler, non-JS answer. Or is the fact that I don't know the height of the image in advance an insurmountable problem? I do know the aspect ratio of the images.

5
  • Make an empty div with a grey background and set dimensions, then add the image as background-image? – Andy Feb 7 '13 at 10:26
  • Tried that as follows, but it doesn't actually seem to do anything: ul.options li { background: url(/media/img/cont/filler.png); background-size: 100% 100%; } – Richard Feb 7 '13 at 10:49
  • Richard, don't use a list item, use a div in place of the <img/>, and then give it set dimensions (height: 200px; width:300px;) and it should work – Andy Feb 7 '13 at 10:55
  • You can't know the width and height of the image until you have loaded the image. It's impossible show the placeholder with exact dimensions that are unknown. If you know the aspect ratio in advance then it's possible the calculate the height. – Jari Pekkala Nov 24 '16 at 15:22
  • height and width attribute for img are basicly made for this (spare ressource for calculating img size and avoid content to jump once image is loaded). You could even update those attributes on server side and inject it in the the tags before the page/html is sent to the browser. if your server runs php : php.net/manual/en/function.getimagesize.php – G-Cyrillus Oct 23 '20 at 18:36

11 Answers 11

30

Instead of referencing the image directly, stick it within a DIV, like the following:

<div class="placeholder">
    <div class="myimage" style="background-image: url({somedynamicimageurl})"><img /></div>
</div>

Then in your CSS:

.placeholder {
    width: 300;
    height: 300;
    background-repeat: no-repeat;
    background-size: contain;
    background-image: url('my_placeholder.png');
}
1
  • 12
    This relies on the non-placeholder image not being transparent, doesn't it? – Medinoc Nov 15 '17 at 19:19
28

Keep in mind - the answers above that recommend using div background approach will change the semantic of your image by turning it from img into a div background. This will result in things like no indexing of these images by search crawler, delay in loading of these images by browser (unless you explicitly preload them), etc.

A solution to this issue (while not using div background approach) is to have a wrapper div to your image and add padding-top to it based on the aspect-ratio of the image that you need to know in advance. Below code will work for image with aspect ratio of 2:1 (height is 50% of width)

<div style="width:100%;height:0; padding-top:50%;position:relative;">
  <img  src="<imgUrl>" style="position:absolute; top:0; left:0; width:100%;">
</div>

Of course - the major disadvantage of this approach is that you need to know the aspect ratio of image in advance.

2
  • 1
    This is the best solution, SEO-wise. – Matt Hagemann Jun 30 '19 at 12:57
  • 1
    This only occupies the area, but does not show a placeholder background image as requested by OP. Simply adding a background-image to the container div wouldnt work either when the image itself contains transparent areas. – phil294 Oct 17 '20 at 14:54
13

There is a really simple thing to check before you start looking into lazy-loading and other JS. Make sure the JPG images you are loading are saved with the 'progressive' option enabled! This will cause them to load the image iteratively, starting with a placeholder that is low-resolution and faster to download, rather than waiting for the highest res data before rendering.

3

It's very simple.. This scenario allows to load profile photo that default placeholder image. You could load multi css background-image into an element. When avatar photo fails, the placeholder image appears default of div.

If you're using a div element that loads via css background-image, you could use this style:

    #avatarImage {
        background-image: url("place-holder-image.png"), url("avatar-image.png");
    }
    <div id="avatarImage"></div>

enter image description here

1
  • 3
    Your answer is about images failing to load, while OP is about placeholder images to show while loading. – phil294 Oct 17 '20 at 14:57
2

The only thing I can think of, to minimize the jump effect on your text, is to set min-height to where the image will appear, I would say - set it to the "shorter" image you know of. This way the jump will be less evident and you won't need to use lazyLoad or so... However it doesn't completely fix your problem.

2

Here's one naive way of doing it,

img { box-shadow: 0 0 10px 0 rgba(#000, 0.1); }

You can manipulate the values, but what it does is it creates a very light border around the image that doesn't push the contents. Images can load at whatever time they want, and you get a good user experience.

Hope that it helps

1
  • A nice idea, but in practice it does not work. You can test it with an image loaded from src="placehold.it/150x150" since they tend to load quite slowly (free service, that's why). Since the DOM does not yet have an object with any size assigned, the box shadow just renders as a small dot (since there is nothing yet to 'shadow') – rmcsharry Sep 6 '16 at 9:43
2

I hope this works. Feel Free to copy this:

<script>
    window.addEventListener("load", function () {
        document.getElementById('image').style.backgroundColor = 'transparent';
    });
</script>

<body>
       <image src="example.example.example" alt="example" id="image" style="background-color:blue;">
</body>

I got this from here: Preloader keeps on loading and doesnt disappear when the content is loaded.

1

Apart from all solutions already mentioned, last solution would be to hide document unlit everything is loaded.

window.addEventListener('load', (e) => {
  document.body.classList.add('loaded');
});
body {
  opacity: 0;
}
body.loaded {
  opacity: 1;
}
<div id="sidebar">
  <img src="http://farm9.staticflickr.com/8075/8449869813_1e62a60f01_b.jpg" />
  <img src="https://www.nla.gov.au/sites/default/files/pic-1.jpg" />
  <img src="https://www.nla.gov.au/sites/default/files/pic-2.jpg" />
  <img src="https://www.nla.gov.au/sites/default/files/pic-3.jpg" />
  <img src="https://www.nla.gov.au/sites/default/files/pic-4.jpg" />
  <img src="https://www.nla.gov.au/sites/default/files/pic-5.jpg" />
  <img src="https://www.nla.gov.au/sites/default/files/pic-6.jpg" />
</div>

or show some animation while everything is loading:

window.addEventListener('load', (e) => {
  document.body.classList.add('loaded');
});
.loader {
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 70px;
  height: 70px;
  -webkit-animation: spin 2s linear infinite;
  /* Safari */
  animation: spin 2s linear infinite;
  position: absolute;
  left: calc(50% - 35px);
  top: calc(50% - 35px);
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

body :not(.loader) {
  opacity: 0;
}

body .loader {
  display: block;
}

body.loaded :not(.loader) {
  opacity: 1;
}

body.loaded .loader {
  display: none;
}
<div class="loader"></div>
<div id="sidebar">
  <img src="http://farm9.staticflickr.com/8075/8449869813_1e62a60f01_b.jpg" />
  <img src="https://www.nla.gov.au/sites/default/files/pic-1.jpg" />
  <img src="https://www.nla.gov.au/sites/default/files/pic-2.jpg" />
  <img src="https://www.nla.gov.au/sites/default/files/pic-3.jpg" />
  <img src="https://www.nla.gov.au/sites/default/files/pic-4.jpg" />
  <img src="https://www.nla.gov.au/sites/default/files/pic-5.jpg" />
  <img src="https://www.nla.gov.au/sites/default/files/pic-6.jpg" />
</div>

0

You can find the width and height of the images in the devtools console, for example in chrome you can click the cursor icon in the devtools console and when you hover on the page it will highlight all the properties of the elements in the page. This will help you find the width and height of the images because if you hover on top of your images it will give you the dimensions of the image and other more properties. You can also make an individual div for each image and make the div relative to the images width and height. You can do it like this:

the main div will contain the images and also the background-div which is below the image.

HTML:

<html>
  <head>
     <meta charset="utf-8">
  </head>
  <body>
      <div class=".mainDiv">
        <div class="below"></div>
        <img src="https://imgix.bustle.com/uploads/image/2020/2/13/da1a1ca4-95ec-40ea-83c1-4f07fac8b9b7-eqb9xdwx0auhotc.jpg" width="500"/>
       </div>
  </body>
</html>

CSS:

.mainDiv {
  position: relative;
}

.below {
  position: absolute;
  background: #96a0aa;
  width: 500px;
  height: 281px;
}

img {
  position: absolute;
}

The result will be that .below will be below the image and so when the image has trouble loading the user will instead see the grey .below div. You cannot see the .below div because it is hidden below the image. The only time you will see this is when the loading of the image is delayed.And this will solve all you problems.

0

I have got a way. But you will need to use javascript for it.

The HTML:

img = document.getElementById("img")
text = document.getElementById("text")
document.addEventListener("DOMContentLoaded", () => {
    img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAA1BMVEWIiIhYZW6zAAAASElEQVR4nO3BgQAAAADDoPlTX+AIVQEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADwDcaiAAFXD1ujAAAAAElFTkSuQmCC";
    text.innerHTML = "Loaded but image is not";
  });
window.onload = function() { 
img.src = "https://media.geeksforgeeks.org/wp-content/uploads/20190913002133/body-onload-console.png";
text.innerHTML = "Image is now loaded";
  };
#img {
    width: 400px;
    height: 300px;
}
<hr>

<img id="img" src="https://media.geeksforgeeks.org/wp-content/uploads/20190913002133/body-onload-console.png">

<p>Here is the Image</p>
<p id="text">Not Loaded</p>

-4
    #avatarImage {
        background-image: url("place-holder-image.png"), url("avatar-image.png");
    }
    <div id="avatarImage"></div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.