这是在Javascript/Jquery(带有动画)中预加载图像的正确方法吗?

这是在Javascript/Jquery(带有动画)中预加载图像的正确方法吗?,javascript,jquery,html,image,preload,Javascript,Jquery,Html,Image,Preload,我正在尝试在加载图像时以html格式显示基本动画 这是正确的方法吗 //display the (small image) animation var preloader = new Image(); preloader.src = 'img/preload.gif'; $('#myDiv').append(preloader); //load big image and hide peload animation when fini

我正在尝试在加载图像时以html格式显示基本动画

这是正确的方法吗

      //display the (small image) animation
      var preloader = new Image();
      preloader.src = 'img/preload.gif';
      $('#myDiv').append(preloader);

      //load big image and hide peload animation when finished
      var img = new Image();
      img.onload = function () { $(preloader).hide(); preloader = null; } ;
      img.src = 'img/bigImage.jpg';
      $('#myDiv').append(img);
我不确定这是否正确:尽管它在我的浏览器中工作,但小动画始终被加载,即使大图像已经加载并在缓存中。有没有一种方法可以取消激活它,或者思考或者其他方法来处理带有小动画的图像预加载

谢谢

以下是我的做法:

var preloader = new Image(),
    img       = new Image(),
    div       = document.getElementById('myDiv');

img.onload = function () {
    preloader = null; 
    div.innerHTML = '';
    div.appendChild(this);
};

img.src = 'img/bigImage.jpg';

// if it's not in cache or not loaded (has no size), show the preloader
if (! (img.complete || img.width+img.height > 0) ) {
    preloader.src = 'img/preload.gif';
    div.innerHTML = '';
    div.appendChild(preloader);
}

您可以启动一个100毫秒的超时,然后检查图像是否已加载。非常好!谢谢,我想指出的是,这样做的好处在于,当您将
img
src
属性重新分配给另一个URL时,它不会导致浏览器检查图像资源的缓存状态。例如,
var i=新图像();i、 src='1〕http://path.to/img.jpg“
。这在我寻找解决方案时帮了我的忙。