这可能是一个非常愚蠢的问题,所以我道歉并准备删除我自己的问题。
我的 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 执行不会停止
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/