等待图像在 JavaScript 中加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2342132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:51:28  来源:igfitidea点击:

Waiting for image to load in JavaScript

javascriptimageloadwait

提问by Jeenyus

I'm making an Ajax call which returns me some info including an image path.

我正在进行 Ajax 调用,它会返回一些信息,包括图像路径。

I prepare all this information in my HTML which will be displayed as a kind of popup. I just toggle the visibility of by popup div from hidden to visible.

我在我的 HTML 中准备了所有这些信息,这些信息将显示为一种弹出窗口。我只是将弹出 div 的可见性从隐藏切换到可见。

To set the position of my popup div, I have to calculate depending on the height of the image. So, I have to wait for the image to load to know its dimension before setting position and switching visibility to visible.

要设置弹出 div 的位置,我必须根据图像的高度进行计算。因此,在设置位置并将可见性切换为可见之前,我必须等待图像加载以了解其尺寸。

I tried tricks with recursion, setTimeout, complete img property, while loop... without success.

我尝试了递归、setTimeout、完整的 img 属性、while 循环……但没有成功。

So, how can I do this? Maybe I should return dimensions in my Ajax call.

那么,我该怎么做呢?也许我应该在我的 Ajax 调用中返回维度。

回答by 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: Firstattach the handler, thenset 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 browsersare 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 srcline 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.)

请注意,按上述顺序执行此操作很重要:首先附加处理程序,然后设置src. 如果您以相反的方式执行此操作,并且图像在缓存中,您可能会错过该事件。JavaScript 在浏览器中的单线程上运行(除非您使用 Web Worker),但浏览器不是单线程的。浏览器看到src,识别资源可用,加载它,触发事件,查看元素以查看它是否有任何需要排队等待回调的处理程序,没有看到任何处理程序,并完成事件,这是完全有效的处理,所有之间src线和附加处理程序的线。(如果它们被注册,回调不会在行之间发生,它们会在队列中等待,但如果没有,则不需要等待事件。)

回答by Sagi

If you use jQuery, you can use its loadevent.

如果你使用 jQuery,你可以使用它的load事件。

Have a look at the example:

看看这个例子:

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

回答by amara mohamed amine

just wrap your image onload in a function with a promise and then call it with await.

只需将您的图像 onload 包装在一个带有 promise 的函数中,然后使用 await 调用它。

async drawImg(ctx, image){

    return new Promise(resolve => {

          image.onload = function () {
                ctx.drawImage(image, 10, 10, 200, 180);
                resolve('resolved');
             }

    });

  }

it should work just fine

它应该工作得很好

回答by 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.

我的页面上加载了一个缓慢的验证码 (1st_image) 图像,我想仅在加载验证码图像 (1st_image) 后显示另一个图像 (2nd_image)。所以我不得不等待验证码(1st_image)图像首先加载。

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

进阶说明:您可以使用图片的“src”中的网页网址,先加载网页,然后再显示图片。目的是从可能影响显示的第二个图像(如 CAPTCHA)的外部网页加载 cookie