用jQuery预加载图像

我正在寻找一种快速简单的方法来用JavaScript预加载图像。如果重要的话,我正在使用jQuery。

我在这里(http://nettuts.com ...看到了

function complexLoad(config, fileNames) {
  for (var x = 0; x < fileNames.length; x++) {
    $("<img>").attr({
      id: fileNames[x],
      src: config.imgDir + fileNames[x] + config.imgFormat,
      title: "The " + fileNames[x] + " nebula"
    }).appendTo("#" + config.imgContainer).css({ display: "none" });
  }
};

但是,对于我想要的东西来说似乎有点过高了!

我知道那里有执行此操作的jQuery插件,但它们看上去都很大(大小);我只需要一种快速,轻松和简短的方式来预加载图像!

神无Green前端2020/03/11 14:44:08

For those who know a little bit of actionscript, you can check for flash player, with minimal effort, and make a flash preloader, that you can also export to html5/Javascript/Jquery. To use if the flash player is not detected, check examples on how to do this with the youtube role back to html5 player:) And create your own. I do not have the details, becouse i have not started yet, if i dont forgot, i wil post it later and will try out some standerd Jquery code to mine.

蛋蛋L2020/03/11 14:44:08

I would use an Manifest file to tell (modern) web browsers to also load all relevant images and cache them. Use Grunt and grunt-manifest to do this automatically and never worry again about preload scripts, cache invalidators, CDN etc.

https://github.com/gunta/grunt-manifest

斯丁前端2020/03/11 14:44:08

I use the following code:

$("#myImage").attr("src","img/spinner.gif");

var img = new Image();
$(img).load(function() {
    $("#myImage").attr("src",img.src);
});
img.src = "http://example.com/imageToPreload.jpg";
小胖阳光2020/03/11 14:44:08

这个jquery imageLoader插件只有1.39kb

用法:

$({}).imageLoader({
    images: [src1,src2,src3...],
    allcomplete:function(e,ui){
        //images are ready here
        //your code - site.fadeIn() or something like that
    }
});

还有其他选项,例如您是否要同步或异步加载图像,以及每个图像的完整事件。