我正在寻找一个快速和简单的方法,预加载图像与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插件在那里做这个,但他们似乎都有点大(大小);我只需要一个快速,简单和短的方式预加载图像!


当前回答

我有一个小插件处理这个。

它被称为waitForImages,它可以处理img元素或CSS中任何引用图像的元素,例如div {background: url(img.png)}。

如果你只是想加载所有的图像,包括在CSS中引用的图像,这里是你如何做的:)

$('body').waitForImages({
    waitForAll: true,
    finished: function() {
       // All images have loaded.
    }  
});

其他回答

我有一个小插件处理这个。

它被称为waitForImages,它可以处理img元素或CSS中任何引用图像的元素,例如div {background: url(img.png)}。

如果你只是想加载所有的图像,包括在CSS中引用的图像,这里是你如何做的:)

$('body').waitForImages({
    waitForAll: true,
    finished: function() {
       // All images have loaded.
    }  
});

我使用以下代码:

$("#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";

你可以在HTML中加载图片,使用CSS display:none;规则,然后显示他们当你想用js或jquery

不使用js或jquery函数预加载只是一个css规则Vs多行js被执行

例如:Html

<img src="someimg.png" class="hide" alt=""/>

Css:

.hide{
display:none;
}

jQuery:

//if want to show img 
$('.hide').show();
//if want to hide
$('.hide').hide();

通过jquery/javascript预加载图像是不好的,因为图像需要几毫秒的时间来加载页面+你有几毫秒的时间来解析和执行脚本,特别是如果它们是大图像,所以隐藏在hml中对性能也更好,因为图像是真正的预加载而不可见,直到你显示出来!

我会使用Manifest文件告诉(现代)网络浏览器也加载所有相关图像并缓存它们。使用Grunt和Grunt -manifest自动完成这个任务,再也不用担心预加载脚本、缓存失效器、CDN等问题。

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

使用JavaScript图像对象。

这个函数允许你在加载所有图片时触发一个回调。但是,请注意,如果至少有一个资源没有加载,它将永远不会触发回调。这可以通过实现onerror回调和增加加载值或处理错误来轻松修复。

var preloadPictures = function(pictureUrls, callback) {
    var i,
        j,
        loaded = 0;

    for (i = 0, j = pictureUrls.length; i < j; i++) {
        (function (img, src) {
            img.onload = function () {                               
                if (++loaded == pictureUrls.length && callback) {
                    callback();
                }
            };

            // Use the following callback methods to debug
            // in case of an unexpected behavior.
            img.onerror = function () {};
            img.onabort = function () {};

            img.src = src;
        } (new Image(), pictureUrls[i]));
    }
};

preloadPictures(['http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar'], function(){
    console.log('a');
});

preloadPictures(['http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar', 'http://foo/picture.bar'], function(){
    console.log('b');
});