用jQuery预加载图像

JavaScript

JinJinDavaid卡卡西

2020-03-11

我正在寻找一种快速简单的方法来用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插件,但它们看上去都很大(大小);我只需要一种快速,轻松和简短的方式来预加载图像!

第692篇《用jQuery预加载图像》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
神无Green前端 2020.03.11

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.

蛋蛋L 2020.03.11

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

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

这个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
    }
});

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android