1
我試圖構建一個簡單的圖像預加載,它會創建一個圖像元素並存儲它,以便以後可以立即使用它。onLoad返回0作爲寬度和高度
我設置這個相當簡單的單例類,我可以使用隨處可見:
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
非常感謝,一直在尋找這個代碼相當長一段時間,並不能看到明顯了。現在它完美地返回寬度和高度! –