我正在尝试构建一个简单的图像预加载,它创建一个图像元素并存储它,以便以后可以立即使用它。
我已经设置了这个相当简单的单例类,我可以在任何地方使用它:
var Preloader = (function() {
var instance = null;
function PrivateConstructor() {
var total = 0;
var onComplete = null;
this.loadImages = function(images, completeHandler) {
total = images.length;
onComplete = completeHandler;
for(var i = 0; i < images.length; i++) {
var img = new Image();
img.onLoad = this.onLoad(img);
img.src = images[i];
}
}
this.onLoad = function(img) {
console.log(img);
console.log(img.width);
console.log(img.height)
total--;
if(total == 0) onComplete();
}
}
return new function() {
this.getInstance = function() {
if (instance == null) {
instance = new PrivateConstructor();
instance.constructor = null;
}
return instance;
}
}
})()
现在当我使用它并检查我的宽度和高度时,它仍然是 0
Preloader.getInstance().loadImages(['https://si0.twimg.com/profile_images/188302352/nasalogo_twitter_bigger.jpg'], function() {
console.log('images loaded');
});
// output
<img src="https://si0.twimg.com/profile_images/188302352/nasalogo_twitter_bigger.jpg">
0
0