简体   繁体   中英

Image width traces zero with onload when cached

I'm building a Javascript lightbox and I'm trying to adjust the size once the image has loaded. I'm using the code below, which works fine - it outputs the correct width once loaded.

My problem:

When I refresh, it will load the image instantly from the cache, and it seems to bypass the load. I get an instant zero for the width. Why does this happen?

My code:

var oImage = new Image();

oImage.src = 'http://mydomain.com/image.png';

container.html(oImage);

oImage.onload = function(){

    alert(this.width);
}

** Update * *

@Alex: This is the code I've tried with your plugin, I assume I'm probably doing something wrong. I'd be eager to get this working because your plugin looks quite good.

container.waitForImages(function() {

    var cWidth = $(this).width();

    alert("width: "+cWidth); // returns 0 - works first time but not cached

});

// Adding the image to the container for preload

container.html('<img src="mygraphic.png" />');

You need to do a few things...

  • Check the complete property of the img element.
  • Attach the load event before setting the src property.

Also, I found creating a new Image and assigning the src there is the best way to determine if the image has loaded or not.

You may want to switch the .html() and the .onload() calls.

If the image is loading from cache, I'm imagining that the .html() call completes before the script has had a chance to attach a function handler to the image's onload event. Therefore, effectively bypassing the load event itself (as the image has already loaded ).

If it's still downloading the image (ie not cached), there will be more than enough time to call the .onload attach before the image completely finishes rendering.

While you're at it, you may want to do this the jQuery way, just so you're attaching events more similarly to DOM2 than DOM0.

var image = $('<img/>', { 
    src : 'http://mydomain.com/image.png'
}).load(function () {
    alert(this.width);
})
// maybe clear container before if you want
.appendTo(container);

If we're going to have to set the src after the onload , we might as well do this instead:

var image = $('<img/>')
    .load(function () {
        alert(this.width);
    })
    .attr('src','http://mydomain.com/image.png')
    .appendTo(container)
    ;

Hopefully that works cleanly.

回答JavaScript:了解图像何时完全加载建议您在设置src之前设置onload

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM