Waiting for image to load in JavaScript

六眼飞鱼酱① 提交于 2019-11-26 22:26:30
Josh Stodola
var img = new Image();
img.onload = function() { alert("Height: " + this.height); }
img.src = "http://path/to/image.jpg";

Note that it's important to do it in the order above: First attach the handler, then set the src. If you do it the other way around, and the image is in cache, you may miss the event. JavaScript is run on a single thread in browsers (unless you're using web workers), but browsers are not single-threaded. It's perfectly valid for the browser to see the src, identify the resource is available, load it, trigger the event, look at the element to see if it has any handlers that need to be queued for callback, not see any, and complete the event processing, all between the src line and the line attaching the handler. (The callbacks wouldn't happen between the lines if they were registered, they'd wait in the queue, but if there aren't any, the event isn't required to wait.)

Sagi

If you use jQuery, you can use its load event.

Have a look at the example:

$('img.userIcon').load(function(){
    if($(this).height() > 100) {
        $(this).addClass('bigImg');
    }
});
Tarik

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!