質問

I'm trying to build a simple image preload which creates an image element and stores it so I can later instantly use it.

I've setup this fairly simple singleton class which I can use everywhere:

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;
    }
}
})()

Now when I use this and check my width and height, it remains 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
役に立ちましたか?

解決

In this line:

img.onLoad = this.onLoad(img);

you are incorrectly calling this.onLoad immediately, rather than passing that function as the load handler. Your code thus completes without ever waiting for the images to be actually loaded.

You also have the case wrong - the handler property should be called img.onload rather than img.onLoad.

Note that the .onload event handler will be called with the image as its this context variable rather than having it passed as a parameter, so you would use this (representing the image, not your class) inside that event handler.

The alternative would be to write:

var self = this;
img.onload = function() {
    self.onLoad(this);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top