javascript - 图片加载完成的那一刻

标签 javascript html image-processing

这可能是一个非常愚蠢的问题,所以我道歉并准备删除我自己的问题。

我的 HTML5 应用程序中有一个图像元素,我为其指定了 'img1' id,如下所示:

<img id="img1" src="" /`>

我将一个模块变量分配给这个元素,如下所示:

var staticImgArray = document.getElementById('img1');

我通过将图像绑定(bind)到通用处理程序来设置图像 src(我使用的是 ASP.NET)

staticImgArray .src = 'get image from this link';

现在我需要知道图像在什么时候完成加载。目前我使用这段代码来确定:

staticImgArray.onload = function () {
   //image has loaded
};
staticImgArray.onerror = function () {
   //image has not loaded properly but has finished trying?
};

但是...

staticImgArray.src = 'get image from this link';
**//image has finished loading here..??**

//other code runs here afterwards

...如果上述说法不成立,那么这是否意味着图像的加载是异步完成的?

谢谢

最佳答案

加载是异步的。这是一个工作示例,显示图像加载后触发 onload 回调,但 js 执行不会停止

fiddle

<小时/>
var staticImgArray = document.getElementById('img1');

staticImgArray.onload = function () {
   //other code after image loads runs here

    console.log('loaded');
};

staticImgArray.src = 'http://static.adzerk.net/Advertisers/c050fce5e0094decb57fdb53f4ca4254.jpg'

console.log('I fire first though');

关于javascript - 图片加载完成的那一刻,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27547001/

相关文章:

javascript - 为什么 nodemailer 发送重复的电子邮件?

javascript - 无法将 Canvas 尺寸设为 1920x1080

javascript - 在鼠标悬停时更改不透明度

html - 将图像放在框旁边 HTML/CSS

jquery - 使用 Javascript 问题粘贴 div

image-processing - 加速旋转图像 - LiveCode

javascript - 动态获取更改的选择值

javascript - 使用嵌套 JSON 响应创建 HTML 列表(具有未定义的 Json 索引级别)?

image - 使用 OpenCV 进行水平线检测

opencv - 应用平滑过滤器(双边、高斯、vs.)和色彩空间