preload images using jQuery

2019-07-21 17:22发布

问题:

I got this snippet of code following a tutorial comment (by James) on Nettuts and I would like to implement it.

The tutorial method of preloading images is long winded but I liked James' shortened version of this, however, I have tried implementing this and I am not getting it right.

It seems I would need to set up my array first, the loop through that array which then creates the image objects and loads them. Yet, when I check my Firebug, I am not seeing any images load into the cache.

$(function(){
      var imgArray = ['bghome01.jpg', 'bghome02.jpg', 'bghome03.jpg'];
        $.preload = function (imgArray) {
            $.each(imgArray, function () {
                alert(imgArray);
                (new Image()).src = 'Images/' + this;
            });
        };
    });

I'd appreciate the help!

回答1:

Right here, you're defining a function, but not calling it:

$.preload = function (imgArray) {

If you just want to load the images, you can slim it down to this:

$(function(){
  var imgArray = ['bghome01.jpg', 'bghome02.jpg', 'bghome03.jpg'];
  $.each(imgArray, function () {
    (new Image()).src = 'Images/' + this;
  });
});

Or, you can do it with your original method, the function definition can be in an external file, but in the page you need to call it, like this:

var imgArray = ['bghome01.jpg', 'bghome02.jpg', 'bghome03.jpg'];
$.preload(imgArray);

I think the confusion here comes from imgArray being the name for the array and the parameter, but these are 2 separate things, it might be less confusing if you gave the parameter to $.preload a different name.



回答2:

My guess is that you don't keep the image objects around, so the garbage collection might throw them away before the image can be loaded.

See this article for some code: http://engineeredweb.com/blog/09/12/preloading-images-jquery-and-javascript

Note that jQuery doesn't do any magic; it's all JavaScript in the end, so something must be wrong with your code. So if keeping the image objects alive doesn't help, maybe this article will point you in the right direction.



回答3:

If I where a browser i would only load images that are on the page, so I suspect his happens because you never add the images to the DOM. Try setting creating a new img-tag with style="visibility:hidden" an add it to the DOM.