等待在Javascript中加载图像 [英] Waiting for image to load in Javascript

查看:92
本文介绍了等待在Javascript中加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进行Ajax调用,它会返回一些信息,包括图像路径。
我在HTML中准备所有这些信息,这些信息将显示为一种弹出窗口。我只是将弹出式div的可见性从隐藏切换为可见。

I'm making an Ajax call which returns me some info including an image path. I prepare all those informations 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.

要设置弹出式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.

我尝试了递归的技巧,setTimeout ,完成img属性,while循环...没有成功。

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

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

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

推荐答案

var img = new Image();
img.onload = function() { alert("Height: " + this.height); }
img.src = "http://path/to/image.jpg";

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

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

这篇关于等待在Javascript中加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆