【发布时间】:2011-11-04 21:34:25
【问题描述】:
我有以下问题。我创建了一个类,我在其构造函数中加载了几个图像,我需要延迟剩余的初始化,直到它们完全加载。我使用的代码如下(摘自构造函数):
var self = this;
var imagesToLoad = 4;
var finishInit = function() {
alert(imagesToLoad);
imagesToLoad--;
if (imagesToLoad == 0) {
// remaining initializations
}
}
this._prevIcon = new Image();
this._prevIcon.onload = finishInit;
this._prevIcon.src = "img1.png";
this._nextIcon = new Image();
this._nextIcon.onload = finishInit;
this._nextIcon.src = "img2.png";
this._pauseIcon = new Image();
this._pauseIcon.onload = finishInit;
this._pauseIcon.src = "img3.png";
this._playIcon = new Image();
this._playIcon.onload = finishInit;
this._playIcon.src = "img4.png";
令我惊讶的是,执行时显示的对话框在 Firefox 7 中显示为 4,4,4,4,在 IE 9 中显示为 4,3,2,4。我很困惑,因为我认为 JS 是单线程的,因此一个事件处理程序不应中断另一个。问题在哪里(或我的错误)?
提前致谢。 最好的祝福, 托梅克
【问题讨论】:
-
尝试在 'src' 和 'onload' 行之间切换。
标签: javascript events