I had a slow CAPTCHA (1st_image) image loading on my page and I wanted to display another image (2nd_image) only AFTER the CAPTCHA image (1st_image) is loaded. So I had to wait for the CAPTCHA (1st_image) image to load first.
Here is the solution that works perfectly fine to wait for an image to load first and then load another image (don't forget to display a "please wait!" image while they are waiting for other image to load):
<script>
function checkImageLoad() {
if (document.getElementById("1st_image").complete == true) {
console.log("1st_image Loaded!");
}
document.getElementById("2nd_image").src = "http://example.org/2nd_image.png";
}
</script>
<body onload="checkImageLoad();">
<img id="1st_image" src="http://example.org/1st_image.png">
<img id="2nd_image" src="http://example.org/loading_please_wait.gif">
Either the Internet speed is slow or fast, and the browser will wait for the whole page to load with all the images (even if they are linked externally) and then execute the function, so the second image is displayed only after the first image loads fine.
Advanced note: You can use a web page URL in the "src" of the image to load a web page first and then show the image. The purpose is to load the cookie from the external webpage which might effect the second image displayed (like CAPTCHA).