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


简单快捷:

function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
        // Alternatively you could use:
        // (new Image()).src = this;
    });
}

// Usage:

preload([
    'img/imageName.jpg',
    'img/anotherOne.jpg',
    'img/blahblahblah.jpg'
]);

或者,如果你想要一个jQuery插件:

$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

// Usage:

$(['img1.jpg','img2.jpg','img3.jpg']).preload();

JP,在检查了您的解决方案后,我仍然在Firefox中有问题,在加载页面之前它不会预加载图像。我是通过在服务器端脚本中添加一些sleep(5)来发现这一点的。我实施了以下解决方案的基础上,似乎解决这个问题。

基本上,我添加了一个回调到你的jQuery预加载插件,这样它就会在所有图像都正确加载后被调用。

// Helper function, used below.
// Usage: ['img1.jpg','img2.jpg'].remove('img1.jpg');
Array.prototype.remove = function(element) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == element) { this.splice(i,1); }
  }
};

// Usage: $(['img1.jpg','img2.jpg']).preloadImages(function(){ ... });
// Callback function gets called after all images are preloaded
$.fn.preloadImages = function(callback) {
  checklist = this.toArray();
  this.each(function() {
    $('<img>').attr({ src: this }).load(function() {
      checklist.remove($(this).attr('src'));
      if (checklist.length == 0) { callback(); }
    });
  });
};

出于兴趣,在我的背景下,我使用这个方法如下:

$.post('/submit_stuff', { id: 123 }, function(response) {
  $([response.imgsrc1, response.imgsrc2]).preloadImages(function(){
    // Update page with response data
  });
});

希望这能帮助那些从谷歌(和我一样)来到这个页面,寻找在Ajax调用上预加载图像的解决方案的人。


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

还有其他选项,比如您想要同步或异步加载图像,以及为每个单独的图像提供完整的事件。


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

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

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

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

谢谢你!我想在J-P的答案上添加一个小riff -我不知道这是否会帮助任何人,但这样你就不必创建一个图像数组,如果你的拇指正确命名,你可以预加载所有的大图像。这很方便,因为我有一个用html编写所有页面的人,它可以确保他们少做一步——消除创建图像数组的需要,以及另一个可能会搞砸的步骤。

$("img").each(function(){
    var imgsrc = $(this).attr('src');
    if(imgsrc.match('_th.jpg') || imgsrc.match('_home.jpg')){
      imgsrc = thumbToLarge(imgsrc);
      (new Image()).src = imgsrc;   
    }
});

基本上,对于页面上的每张图像,它都会抓取每张图像的src,如果它符合某些条件(是拇指,或主页图像),它会更改名称(图像src中的基本字符串替换),然后加载图像。

在我的例子中,页面上满是拇指图像,它们的名称都类似image_th.jpg,而所有相应的大图像的名称都是image_lg.jpg。thumb to large只是将_th.jpg替换为_lg.jpg,然后预加载所有大图像。

希望这能帮助到一些人。


下面是第一个响应的调整版本,它实际将图像加载到DOM中并默认隐藏它。

function preload(arrayOfImages) {
    $(arrayOfImages).each(function () {
        $('<img />').attr('src',this).appendTo('body').css('display','none');
    });
}

这一行jQuery代码创建(并加载)一个DOM元素img,但没有显示它:

$('<img src="img/1.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中对性能也更好,因为图像是真正的预加载而不可见,直到你显示出来!


function preload(imgs) {
    $(imgs).each(function(index, value) {
        $('<img />').attr('src', value).appendTo('body').css('display', 'none');
    });
}

.attr(“src”,值) 不 .attr(“src”,这个)

只是指出一点:)


用jQuery预加载图像并获得回调函数的一个快速、无插件的方法是一次性创建多个img标记并计算响应。

function preload(files, cb) {
    var len = files.length;
    $(files.map(function(f) {
        return '<img src="'+f+'" />';
    }).join('')).load(function () {
        if(--len===0) {
            cb();
        }
    });
}

preload(["one.jpg", "two.png", "three.png"], function() {
    /* Code here is called once all files are loaded. */
});
​    ​

注意,如果你想支持IE7,你需要使用这个稍微不那么漂亮的版本(它也适用于其他浏览器):

function preload(files, cb) {
    var len = files.length;
    $($.map(files, function(f) {
        return '<img src="'+f+'" />';
    }).join('')).load(function () {
        if(--len===0) {
            cb();
        }
    });
}

使用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');
});

即使在IE9中,这也适用于我:

$('<img src="' + imgURL + '"/>').on('load', function(){ doOnLoadStuff(); });

    jQuery.preloadImage=function(src,onSuccess,onError)
    {
        var img = new Image()
        img.src=src;
        var error=false;
        img.onerror=function(){
            error=true;
            if(onError)onError.call(img);
        }
        if(error==false)    
        setTimeout(function(){
            if(img.height>0&&img.width>0){ 
                if(onSuccess)onSuccess.call(img);
                return img;
            }   else {
                setTimeout(arguments.callee,5);
            }   
        },0);
        return img; 
    }

    jQuery.preloadImages=function(arrayOfImages){
        jQuery.each(arrayOfImages,function(){
            jQuery.preloadImage(this);
        })
    }
 // example   
    jQuery.preloadImage(
        'img/someimage.jpg',
        function(){
            /*complete
            this.width!=0 == true
            */
        },
        function(){
            /*error*/
        }
    )

$.fn.preload = function (callback) {
  var length = this.length;
  var iterator = 0;

  return this.each(function () {
    var self = this;
    var tmp = new Image();

    if (callback) tmp.onload = function () {
      callback.call(self, 100 * ++iterator / length, iterator === length);
    };

    tmp.src = this.src;
  });
};

用法很简单:

$('img').preload(function(perc, done) {
  console.log(this, perc, done);
});

http://jsfiddle.net/yckart/ACbTK/


我使用以下代码:

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

我想用谷歌地图API自定义覆盖来做到这一点。他们的示例代码简单地使用JS插入IMG元素,并显示图像占位符框,直到图像被加载。我在这里找到了一个适合我的答案:https://stackoverflow.com/a/10863680/2095698。

$('<img src="'+ imgPaht +'">').load(function() {
$(this).width(some).height(some).appendTo('#some_target');
});

这将像前面建议的那样预加载图像,然后在加载img URL后使用处理程序追加img对象。jQuery的文档警告说,缓存的图像不能很好地与这个事件/处理程序代码一起工作,但它在FireFox和Chrome中为我工作,我不必担心IE。


5行coffescript

array = ['/img/movie1.png','/img/movie2.png','/img/movie3.png']

$(document).ready ->
  for index, image of array
    img[index] = new Image()
    img[index].src = image

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

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


对于那些知道一点点actionscript的人,你可以检查flash播放器,用最小的努力,并制作一个flash预加载器,你也可以导出到html5/Javascript/Jquery。 如果flash播放器未被检测到,请检查如何将youtube角色返回到html5 player的示例:) 并且创造你自己的。 我没有细节,因为我还没有开始,如果我不忘记,我将张贴它以后,并将尝试一些标准的Jquery代码我。


我通常在我的项目中使用这段代码来加载页面中的图像。 你可以在这里看到结果https://jsfiddle.net/ftor34ey/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<img src="https://live.staticflickr.com/65535/50020763321_d61d49e505_k_d.jpg" width="100" />
<img src="https://live.staticflickr.com/65535/50021019427_692a8167e9_k_d.jpg" width="100" />
<img src="https://live.staticflickr.com/65535/50020228418_d730efe386_k_d.jpg" width="100" />
<img src="https://live.staticflickr.com/65535/50020230828_7ef175d07c_k_d.jpg" width="100" />

<div style="background-image: url(https://live.staticflickr.com/65535/50020765826_e8da0aacca_k_d.jpg);"></div>
<style>
    .bg {
        background-image: url("https://live.staticflickr.com/65535/50020765651_af0962c22e_k_d.jpg");
    }
</style>
<div class="bg"></div>

<div id="loadingProgress"></div>

脚本将页面的所有src和background-image保存在一个数组中并加载它们。

你可以通过var loadCount查看/读取/显示加载的进度。

let backgroundImageArray = [];

function backgroundLoading(i) {

    let loadCount = 0;

    let img = new Image();
    $(img).on('load', function () {

        if (i < backgroundImageArray.length) {

            loadCount = parseInt(((100 / backgroundImageArray.length) * i));
            backgroundLoading(i + 1);

        } else {

            loadCount = 100;
            // do something when the page finished to load all the images
            console.log('loading completed!!!');
            $('#loadingProgress').append('<div>loading completed!!!</div>');

        }

        console.log(loadCount + '%');
        $('#loadingProgress').append('<div>' + loadCount + '%</div>');

    }).attr('src', backgroundImageArray[i - 1]);

}

$(document).ready(function () {

    $('*').each(function () {

        var backgroundImage = $(this).css('background-image');
        var putInArray = false;

        var check = backgroundImage.substr(0, 3);

        if (check == 'url') {

            backgroundImage = backgroundImage.split('url(').join('').split(')').join('');
            backgroundImage = backgroundImage.replace('"', '');
            backgroundImage = backgroundImage.replace('"', '');

            if (backgroundImage.substr(0, 4) == 'http') {
                backgroundImage = backgroundImage;
            }
            putInArray = true;

        } else if ($(this).get(0).tagName == 'IMG') {

            backgroundImage = $(this).attr('src');
            putInArray = true;

        }

        if (putInArray) {
            backgroundImageArray[backgroundImageArray.length] = backgroundImage;
        }

    });

    backgroundLoading(1);

});