Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best approach to display the image after it is loaded [closed]

Tags:

javascript

Currently I see there are two ways we can show the image after it is loaded.

First Approach

<img id="myImage" />

var img = new Image(),
    x = document.getElementById("myImage");

img.onload = function() {
   x.src = img.src;
};

img.src = "http://somedomain/image.jpg";

Second Approach

<img id="myImage" src="http://somedomain/image.jpg" style="display:none" onload="showImage();" />

function showImage() {
  document.getElementById("myImage").style.display = 'block';
}

I'm little confused which one is the better approach? In some examples I found online they uses the first approach but I see the second approach is very simple. Is there any drawbacks exist in the second approach?

like image 544
VJAI Avatar asked Dec 05 '25 07:12

VJAI


1 Answers

First approach is better from a re-usability of code point of view.

You can use the img variable for other images as well if multiple Img tags are going to point to the same images such as showing delete icon for line items.

Second approach is better from the point of view of usability.

You can show a different (already available) image like loading or a default user-avatar till the image is actually downloaded and available.

Also, with the second approach you can fade-in or slide-up images when the onload event is invoked, which you can't do with first approach.

like image 103
gurvinder372 Avatar answered Dec 06 '25 22:12

gurvinder372



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!