高速缓存时,图像宽度跟踪为零

JCr*_*ine 4 javascript jquery load image loading

我正在构建一个Javascript灯箱,我试图在图像加载后调整大小.我正在使用下面的代码,它工作正常 - 一旦加载它输出正确的宽度.

我的问题:

当我刷新时,它会立即从缓存加载图像,它似乎绕过了负载.我的宽度瞬间为零.为什么会这样?

我的代码:

var oImage = new Image();

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

container.html(oImage);

oImage.onload = function(){

    alert(this.width);
}
Run Code Online (Sandbox Code Playgroud)

**更新**

@Alex:这是我用你的插件试过的代码,我想我可能做错了.我渴望得到这个,因为你的插件看起来很不错.

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" />');
Run Code Online (Sandbox Code Playgroud)

ale*_*lex 5

你需要做一些事......

  • 检查元素的complete属性img.
  • load在设置src属性之前附加事件.

此外,我发现创建一个新的Image并分配src有确定图像是否已加载的最佳方法.